2016-02-13 42 views
0

我正在使用sql-server 2012,並且在更新表中有一個奇怪的問題。執行更新查詢後,子查詢返回了超過1個值的錯誤

我的選擇查詢返回的行樹,猶如如下:

select * from 
    TAble1 p join 
    (select ProductId=max(ProductId) from Table2 s group by s.ProductId) pin on p.id=pin.ProductId 
    where p.categoryid=238 

和返回的行:

enter image description here

現在,當我運行此更新查詢:

update TAble1 set sizing=0 from 
    TAble1 p join 
    (select ProductId=max(ProductId) from TAble2 s group by s.ProductId) pin on p.id=pin.ProductId 
    where p.categoryid=238 

我得到這個錯誤:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. 
The statement has been terminated. 

問題在哪裏查詢?

回答

2

看起來像生成異常的問題在其他地方(例如觸發器內部)。

此行可能是爲什麼有超過一排更新

(select ProductId=max(ProductId) from TAble2 s group by s.ProductId) 

如果你想獲得最大的ProductID(單個值)的原因 - 從組中刪除BY子句。目前,您正在請求服務器從單個值返回最大值 - 這是荒謬的。它只是返回Table2中所有ProductID值的列表。這是一樣的

select distinct ProductID from Table2 
+0

這是一個觸發器。謝謝! – Mashtani

+0

觸發器在一行更新或其他東西后運行? – Mashtani

+0

它在統計之後運行,無論它是更改一行還是更多。 –

0

select ProductId=max(ProductId) from Table2 s group by s.ProductId 會給你DISTINCT產品編號的,但不是MAX。而且你沒有鏈接TAble1實際上你的查詢將更新所有TAble1.sizing列。 試試這個:

UPDATE TAble1 
SET sizing = 0 
FROM TAble1 p 
JOIN 
    (SELECT max(s.ProductId) AS ProductId 
    FROM TAble2) pin 
     ON p.id = pin.ProductId AND p.categoryid=238 
WHERE p.categoryid = categoryid 
0

我想一個更好的問題是什麼,是不是在你的查詢問題。在你的SELECT中,你應該加入什麼?你和什麼索引加入?您正在使用GROUP BY,但不包括GROUP BY作爲SELECT中的列。您不需要在子查詢中爲'TAble2 s'別名。 TAble p沒有基於您所展示的內容的categoryid列。在大多數情況下,您不應該在UPDATE查詢中需要FROM子句,尤其是因爲您只是將列設置爲靜態值。

但是要回答你的問題:子查詢:「從s.ProductId從TAble2組中選擇ProductId = max(ProductId)」將返回所有ProductId行,因此在嘗試加入時會失敗。

既然你不使用從表2的信息,爲什麼不只是單純地喜歡這個更新:

update TAble1 set sizing=0 where categoryid=238 
相關問題