2

我通过从表中选择数据并插入另一个来更新数据。但是,另一张桌子上有一些限制,我得到了这个:

DETAIL:  Key (entry_id)=(391) is duplicated.

我基本上是这样做的:

insert into table_tmp 
select * from table_one

发生此键条目重复时如何跳过插入?

更新我无法在 SQL fiddle 上保存此架构信息,但它是:

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

如果我尝试构建架构会出现错误

4

2 回答 2

2

使用此查询 - SQLFiddle 演示

INSERT INTO table2 
SELECT t1.* FROM table1 t1
WHERE NOT EXISTS (
    SELECT entry_id
    FROM table2 t2
    WHERE t2.entry_id = t1.entry_id
)
于 2013-11-01T10:24:07.017 回答
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
于 2013-11-01T10:30:42.960 回答