[英]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.