如何从子查询更新多行?

时间:2018-02-23 09:36:07

标签: sql db2

我现在正在使用DB2并尝试更新多行,但在查询下方返回SQL0811N,即

标量全选,SELECT INTO语句或VALUES INTO语句的结果不止一行"。

我正在寻找可以通过子查询选择的每个值更新多行的查询。

update
    table_004
set
    status = 99,
    bar_date = (
        select
            max(foo_date) as bar_date
        from
            table_001 t1
            inner join
                table_002 t2
            on  t1.keyA = t2.keyA
            inner join
                table_003 t3
            on  t2.keyA = t3.keyA
            inner join
                table_004 t4
            on  t4.keyB = t3.keyB
        where
            t1.id in(1, 2, 3, 4, 5)
        group by
            t1.id,
            t4.keyB
    )

2 个答案:

答案 0 :(得分:1)

您的表004不需要进入子选择。试试这个:

update table_004 t4
set (t4.status, t4.bar_date) =
(
    select  99,  max(foo_date)
    from table_001 t1
    inner join table_002 t2 on  t1.keyA = t2.keyA
    inner join table_003 t3 on  t2.keyA = t3.keyA
    where t1.id in(1, 2, 3, 4, 5) and t4.keyB = t3.keyB
    group by t1.id
)
where exists
(
    select *
    from table_001 t1
    inner join table_002 t2 on  t1.keyA = t2.keyA
    inner join table_003 t3 on  t2.keyA = t3.keyA
    where t1.id in(1, 2, 3, 4, 5) and t4.keyB = t3.keyB
)

答案 1 :(得分:0)

我添加了

  • 比较我要更新的表与子查询中使用的表之间的id的条件
  • app.block.service.patrick: class: AppBundle\Block\PatrickBlockService arguments: - "Patrick Block" - "@templating" 条款where声明

并且查询已经完全按照我的要求执行。万岁!

编辑过的SQL:

update