First, to find the intersection of Table1 and Table2 I have
SELECT Id FROM Table1
INTERSECT
SELECT Id FROM Table2
or
SELECT Table1.Id
FROM Table1
INNER JOIN Table2 ON Table1.Id=Table2.Id
Now I want to insert that into table3:
INSERT INTO Table3
SELECT Table1.Id
FROM Table1
INNER JOIN Table2 ON Table1.Id=Table2.Id
But the problem is that some Id I am trying to insert can be already in Table3 (and Id is the primary key, so it must be unique).
I have read https://stackoverflow.com/a/5288322/1529630 . Then, I have renamed Id to Id_ in Table3 to avoid conficts so that I can do
SELECT DISTINCT Id
FROM Table1 cr LEFT JOIN Table3 c ON cr.Id = c.Id_
WHERE c.Id_ IS NULL
But when I try to intersect...
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
...I get an error. What I am doing wrong? Is there a better way to do it?
If the problem is uniqueness of ids, try something like this:
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);
EDIT:
I proposed the above because it seems the clearest way of expressing what you want. The equivalent using left outer join
might perform better:
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
You can also use INSERT OR IGNORE
to ignore the error:
INSERT OR IGNORE INTO Table3(id)
SELECT Table1.Id
FROM Table1 INNER JOIN
Table2
ON Table1.Id=Table2.Id;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.