![](/img/trans.png)
[英]Subquery returned more than 1 value. This is not permitted when the subquery follows … or when the subquery is used as an expression
[英]SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows (chars) or when the subquery is used as an expression
我試圖根據它們的出現更新一些字段。 如果它們只出現一次,我正在更新一些狀態字段。
我目前的代碼如下:
UPDATE table1
SET statusField = 1
WHERE someID = (
SELECT someID
FROM table1
GROUP BY someID HAVING COUNT(*) = 1
)
這將返回一個錯誤,如標題中的錯誤: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
還有其他易於閱讀/簡單的解決方案嗎?
使用IN
關鍵字而不是equals運算符,如下所示:
UPDATE table1
SET statusField = 1
WHERE someID IN (
SELECT someID
FROM table1
GROUP BY someID HAVING COUNT(*) = 1
)
使用=
要求子查詢返回1個結果。 IN
關鍵字適用於列表。
您應該在子選擇中加入表格。 可以使用'in',但在你的情況下我會使用exists:
UPDATE table1 x
SET statusField = 1
WHERE exists (
SELECT null
FROM table1
WHERE x.someID = someID
GROUP BY someID
HAVING COUNT(*) = 1
)
為了獲得更好的性能,我會使用這個腳本(sqlserver-2008 +):
;WITH x as
(
SELECT rc = count() over (partition by someID), statusField
FROM table1
)
UPDATE x
SET statusField = 1
WHERE rc = 1
嘗試這個
使用Top
UPDATE table1
SET statusField = 1
WHERE someID = (
SELECT TOP 1 someID
FROM table1
GROUP BY someID HAVING COUNT(*) = 1
)
或者你可以使用IN子句
UPDATE table1
SET statusField = 1
WHERE someID IN (
SELECT someID
FROM table1
GROUP BY someID HAVING COUNT(*) = 1
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.