代码之家  ›  专栏  ›  技术社区  ›  Krushna

如何使用max+1语法从返回多行的slect结果写入insert查询

  •  0
  • Krushna  · 技术社区  · 7 年前

    我正试图在DB2中编写一个如下所示的SQL。

    insert into tableA (col1, col2, col3) 
        select max(col1) + 1, '-2', col3 
        from tableA 
        where col2 = -1
    

    这里的目标是将tableA的所有记录从-1复制到-2,这里的col1是主键,应该递增1。

    现在的问题是select查询将返回多行,如下所示

    1001 -2 xyz
    1001 -2 pqr
    1001 -2 xdc
    

    由于键相同,因此无法插入。

    是否有任何方法可以编写select sql,以便它可以像下面这样返回

      1001 -2 xyz
      1002 -2 pqr
      1003 -2 xdc
    

    而我的插入将起作用,或者是否有任何替代方法,以最简单的方式相同。

    注意:该表没有任何触发器或自动递增主键的东西。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Gordon Linoff    7 年前

    对使用 row_number() :

    insert into tableA ( col1, col2, col3)
        select max(col1) + row_number() over (order by col3), '-2', col3
        from tableA
        where col2 = -1
        group by col3;
    

    如果你没有 group by ,然后执行:

    insert into tableA ( col1, col2, col3)
        select  maxcol1 + row_number() over (order by col3), '-2', col3
        from (select a.*, max(col1) over () as maxcol1
              from tableA a
             ) a
        where col2 = -1;
    

    正确的方法是使用生成的自动递增值 col1 。如果多个线程试图同时进行插入,那么这些代码都会出现问题。

        2
  •  0
  •   Usman    7 年前

    尝试此查询!

    insert into tableA (col1, col2, col3) 
        select (max(col1) + 1) as col1, '-2' as col2, col3 
        from tableA 
        where col2 = -1