【问题标题】:Update statement for multiple ids多个 id 的更新语句
【发布时间】:2012-05-11 19:07:24
【问题描述】:

我有 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;

这个查询工作正常,它会更新第三个表列,但是如果我提供这样的 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);

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

子查询返回超过 1 个值。当子查询跟随 =、!=、、>= 或子查询用作表达式时,这是不允许的。 声明已终止。

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

如何更新多个 ID? IE。 ID 100 返回的选择查询值应针对第三个表中的 ID 100 进行更新,对于 ID 101 也是如此。

另外,我需要像这样 sum(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);

【问题讨论】:

  • 你说得对,我不需要内部 id 条件。

标签: sql sql-server sql-server-2008 tsql sql-server-2005


【解决方案1】:

这是因为您试图将 column3 设置为返回的结果,而 SQL 期望它仅为一个值(标量)。当您向 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)

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

【讨论】:

    【解决方案2】:

    您还应该在您的UPDATE 中加入table3。试试这个:

    UPDATE t3
    SET column3 = t2.column3+t1.column3
    FROM table3 t3
    INNER JOIN table2 t2 WITH(NOLOCK) 
    ON t3.id = t2.id
    INNER JOIN table1 t1
    ON t3.id=t1.id
    WHERE t3.id IN (100,101)
    

    【讨论】:

    • 这非常接近,我试过了,不知怎的我明白了。我需要做这样的总和 sum(t2.column3)- (t1.column3 + t1.column2)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    相关资源
    最近更新 更多