0

I have 3 tables. Two tables (par1, par1) both refer (child_id) to an id in the 3rd table (child).

I like to find orphans in the 3rd table, i.e. records that are not referenced by either of the other two tables.

If I had only once referencing table, I could write:

SELECT * FROM child WHERE id NOT IN (SELECT child_id FROM par1)

But how do I solve this for two referencing tables?

I'm using sqlite.

4

2 回答 2

5
SELECT * 
FROM child 
WHERE id NOT IN (SELECT child_id FROM par1) AND 
      id NOT IN (SELECT child_id FROM par2)
于 2013-05-28T23:21:14.643 回答
1

另一种方法是使用 LEFT OUTER JOIN:

SELECT child.*
FROM child LEFT OUTER JOIN par1 ON (child.id = par1.child_id)
           LEFT OUTER JOIN par2 ON (child.id = par2.child_id)
WHERE par1.child_id IS NULL AND par2.child_id IS NULL

执行子查询可能会也可能不会在 SQLite 索引决策引擎中找到所需的优化路径。

于 2015-11-20T23:15:05.920 回答