除了Table3中已存在的条目外,如何将Table1和Table2的交集插入Table3?

时间:2013-07-13 19:57:03

标签: sql sqlite pdo insert

首先,找到Table1和Table2的交集我有

SELECT Id FROM Table1
INTERSECT
SELECT Id FROM Table2

SELECT Table1.Id
    FROM Table1
    INNER JOIN Table2 ON Table1.Id=Table2.Id

现在我想将其插入table3:

INSERT INTO Table3
SELECT Table1.Id
    FROM Table1
    INNER JOIN Table2 ON Table1.Id=Table2.Id

但问题是我尝试插入的一些Id可能已经在Table3中(并且Id是主键,所以它必须是唯一的。)

我看过https://stackoverflow.com/a/5288322/1529630。然后,我在表3中将Id重命名为Id_以避免混淆,以便我可以

SELECT DISTINCT Id
FROM Table1 cr LEFT JOIN Table3 c ON cr.Id = c.Id_
WHERE c.Id_ IS NULL

但是当我试图相交时......

SELECT Id FROM Table2

INTERSECT

SELECT DISTINCT Id
FROM Queue cr LEFT JOIN Excluded c ON cr.Id = c.Id_
WHERE c.Id_ IS NULL

......我收到错误。我做错了什么?有没有更好的方法呢?

1 个答案:

答案 0 :(得分:1)

如果问题是ids的唯一性,请尝试以下方法:

INSERT INTO Table3(id)
    SELECT Table1.Id
    FROM Table1 INNER JOIN
         Table2
         ON Table1.Id=Table2.Id
    where Table1.Id not in (select Id from Table3);

编辑:

我提出了上述内容,因为它似乎是表达你想要的最清晰的方式。使用left outer join的等效项可能会更好:

INSERT INTO Table3(id)
    SELECT Table1.Id
    FROM Table1 INNER JOIN
         Table2
         ON Table1.Id=Table2.Id left outer join
         Table3
         on Table1.id = Table3.id
    where Table3.id is null

您也可以使用INSERT OR IGNORE忽略错误:

INSERT OR IGNORE INTO Table3(id)
    SELECT Table1.Id
    FROM Table1 INNER JOIN
         Table2
         ON Table1.Id=Table2.Id;