如何将表格分散到另一个表格中

时间:2016-04-22 10:08:54

标签: sql postgresql

我们有一张遗产表

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”

任何想法如何做到这一点?如果table2的行数少于table1

,那么如果table1保留一些行col2 = null,那就没关系

2 个答案:

答案 0 :(得分:0)

我想我找到了一个解决方案

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
    )
) 

有关它的任何缺点吗?

答案 1 :(得分:0)

使用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;

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

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;