【问题标题】:How to spread a table into another one如何将一张桌子展开到另一张桌子上
【发布时间】:2016-04-22 10:08:53
【问题描述】:

我们有一张旧表

create table table1 (col1 int);
insert into table1 values(1);
insert into table1 values(2);
insert into table1 values(3);

SELECT * FROM table1;
1
2
3

现在它有了一个新列

alter table table1 add column col2 int;
alter table table1  ADD CONSTRAINT unique1 UNIQUE (col2);

SELECT * FROM table1;
1;null
2;null
3;null

然后我们有另一个表

create table table2 (col1 int);
insert into table2 values(7);
insert into table2 values(8);
insert into table2 values(9);

SELECT * FROM table2;
7
8
9

现在我们要将表 2 的值传播到 table1.col2 中

UPDATE table1 up
SET col2 = (SELECT col1
            FROM table2 t2
            WHERE NOT EXISTS (SELECT 1 FROM table1 t1 WHERE t1.col2=t2.col1)
            LIMIT 1);

但是更新语句看不到已经更新的行

错误:重复键值违反唯一约束“unique1”

任何想法如何做到这一点?没关系,如果 table1 保留一些行 col2=null 如果 table2 的行数少于 table1

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    join 似乎更容易:

    with t2 as (
          select t2.*, row_number() over (order by col1) as seqnum
          from table2 t2
         )
    update table1 t1
        set col2 = t2.col1
        from t2
        where t1.col1 = t2.seqnum;
    

    如果table1 中的col1 不是严格顺序的,您仍然可以这样做:

    with t2 as (
          select t2.*, row_number() over (order by col1) as seqnum
          from table2 t2
         ),
         t1 as (
          select t1.*, row_number() over (order by col1) as seqnum
          from table1 t1
         )
    update table1 toupdate
        set col2 = t2.col1
        from t1 join
             t2
             on t1.seqnum = t2.seqnum
        where toupdate.col1 = t1.col1;
    

    【讨论】:

      【解决方案2】:

      我想我找到了解决办法

      WITH rownumbers AS (
          SELECT col1, row_number() over (partition by 1 ORDER BY col1) FROM table1
      )
      UPDATE table1 up SET col2 = 
          (SELECT col1 FROM table2 t2 WHERE NOT EXISTS (SELECT 1 FROM table1 t1 WHERE t1.col2=t2.col1) 
          LIMIT 1 OFFSET (
                  SELECT row_number-1 FROM rownumbers WHERE col1=up.col1
          )
      ) 
      

      有什么缺点吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-09
        • 2020-07-29
        • 2015-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-03
        • 2012-05-23
        相关资源
        最近更新 更多