【发布时间】: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