子查询返回了多个值 - where子句

时间:2013-04-09 22:58:19

标签: sql sql-update subquery

我有一个查询来停用某些已激活的帐户。基本上它会查看year_end_close表,并且那里存在的任何帐户都会在主表中更新为非活动状态(A或B)。

update master
 set account_type = case account_type
  when 'C' then 'A'
  when 'D' then 'B'
  else account_type
 end
where account_num = 
      (select account_num 
       from year_end_close 
       where account_type in('C', 'D'))`

我从where子句得到“Subquery返回的值超过1” - 我做错了什么?当我注释掉where子句时,我不再得到那个错误,所以这是该子句中的内容。

3 个答案:

答案 0 :(得分:2)

将您的=更改为IN

UPDATE master
SET account_type =
   CASE account_type
      WHEN 'C' then 'A'
      WHEN 'D' then 'B'
      ELSE account_type
   END
WHERE account_num IN
(
   SELECT account_num
   FROM year_end_close
   WHERE account_type IN('C', 'D')
)

使用=表示您要将=左侧的1个项目与右侧的1个项目进行比较。 account_num中有多个year_end_closeaccount_typeC D。这使您的子查询返回多于1个结果。查询无法确定子查询中的哪个值应与左侧的值匹配。使用IN允许查询检查子查询中任何有效account_num的左值。

答案 1 :(得分:0)

尝试IN而不是检查相等性:

update master
 set account_type = case account_type
  when 'C' then 'A'
  when 'D' then 'B'
  else account_type
 end
where account_num IN (select account_num from year_end_close where account_type in('C', 'D'))`

......虽然它取决于您的数据/架构。

答案 2 :(得分:0)

@matt和@Adam的其他答案都是正确的 - 如果您坚持使用子查询,则需要使用In而不是=。但我认为这与:

相同
UPDATE m Set
   account_type = 
    Case account_type
       WHEN 'C' then 'A'
       WHEN 'D' then 'B'
       ELSE account_type END
From master m Join year_end_close c
    On c.account_num  = m.account_num 
       And c.account_type in ('C', 'D')

编辑:此语法在MS Sql Server中有效,但可能无法在所有其他供应商的数据库产品中使用。        你使用的是哪个数据库?

相关问题