我正在通过从表中选择数据并插入另一个数据来更新数据。但是在另一个表上存在一些限制,我得到了这个:
DETAIL: Key (entry_id)=(391) is duplicated.
我基本上这样做:
insert into table_tmp
select * from table_one
如果发生此密钥输入重复,我如何跳过插入?
更新我无法在SQL小提琴上保存此架构信息,但现在是:
CREATE TABLE table1
("entry_id" int, "text" varchar(255))
;
INSERT INTO table1
("entry_id", "text")
VALUES
(1, 'one'),
(2, 'two'),
(3, 'test'),
(3, 'test'),
(12, 'three'),
(13, 'four')
;
CREATE TABLE table2
("entry_id" int, "text" varchar(255))
;
Create unique index entry_id_idxs
on table2 (entry_id)
where text='test';
INSERT INTO table2
("entry_id", "text")
VALUES
(1, 'one'),
(2, 'two'),
(3, 'test'),
(3, 'test'),
(12, 'three'),
(13, 'four')
;
如果我尝试构建架构,我会收到错误
答案 0 :(得分:2)
使用此查询 - SQLFiddle Demo:
INSERT INTO table2
SELECT t1.* FROM table1 t1
WHERE NOT EXISTS (
SELECT entry_id
FROM table2 t2
WHERE t2.entry_id = t1.entry_id
)
答案 1 :(得分:2)
使用返回不匹配行的连接插入:
INSERT INTO table2
SELECT DISTINCT t1.*
FROM table1 t1
LEFT JOIN table2 t2 ON t2.entry_id = t1.entry_id
WHERE t2.entry_id IS NULL