更新多个ID的语句

Sha*_*500 4 sql t-sql sql-server sql-server-2005 sql-server-2008

我有3个表,我需要通过计算来自其他两个表的数据来更新第3个表的列.

update table3 set column3=
(
select t2.column3+t1.column3
from table2 t2 with (nolock) join table1 t1
on table2.id=t1.id
where table2.id= 100
)
where id= 100;
Run Code Online (Sandbox Code Playgroud)

这个查询工作正常,它会更新第3个表列,但是如果我提供这样的IN运算符:

  update table3 set column3=
    (
    select t2.column3+t1.column3
    from table2 t2 with (nolock) join table1 t1
    on table2.id=t1.id
    where table2.id IN (100,101)
    )
    where id IN (100,101);
Run Code Online (Sandbox Code Playgroud)

这失败了,我收到了这条消息

子查询返回的值超过1.当子查询跟随=,!=,<,<=,>,> =或子查询用作表达式时,不允许这样做.该语句已终止.

我知道这是因为子查询返回超过1行,我该如何处理这种情况?任何暗示/想法都会有所帮助.

如何更新多个ID?即.ID 100返回的选择查询值应该针对第3表中的ID 100进行更新,类似地针对ID 101进行更新.

另外,我需要做这样的总和(t2.column3) - (t1.column3 + t1.column2)

 update table3 set column3=
        (
        select  sum(t2.column3)- (t1.column3 + t1.column2)
        from table2 t2 with (nolock) join table1 t1
        on table2.id=t1.id
        where table2.id IN (100,101)
        )
        where id IN (100,101);
Run Code Online (Sandbox Code Playgroud)

Jus*_*ony 6

这是因为您尝试设置column3为返回的结果,并且SQL期望它只是一个值(标量).当你传递多个返回值时,SQL引擎会感到困惑(应该使用哪一个?...它不会假设迭代结果).因此,如果要更新整个结果集,则需要从查询创建子表并加入该子表.您的查询看起来应该更像这样

UPDATE Table3
SET Column3 = subtable.value
FROM Table3 
    JOIN (
        select t2.column3+t1.column3 as value, t1.id
        from table2 t2 with (nolock) join table1 t1
        on table2.id=t1.id
        where table2.id IN (100,101)
    ) AS subtable
    ON subtable.id = Table3.id
WHERE table3.id IN (100, 101)
Run Code Online (Sandbox Code Playgroud)

在这个假设下table3.id匹配其他id,你也真的不需要内部 where table2.id IN ...