【发布时间】:2009-04-17 15:42:33
【问题描述】:
我有一个包含唯一 ID 字段的表。另一个字段 (REF) 包含对另一个数据集 ID 字段的引用。 现在我必须选择 REF 指向不存在的数据集的所有数据集。
SELECT * FROM table WHERE ("no dataset with ID=REF exists")
我该怎么做?
【问题讨论】:
标签: sql
我有一个包含唯一 ID 字段的表。另一个字段 (REF) 包含对另一个数据集 ID 字段的引用。 现在我必须选择 REF 指向不存在的数据集的所有数据集。
SELECT * FROM table WHERE ("no dataset with ID=REF exists")
我该怎么做?
【问题讨论】:
标签: sql
三种方式
SELECT * FROM YourTable y WHERE NOT EXISTS
(SELECT * FROM OtherTable o WHERE y.Ref = o.Ref)
SELECT * FROM YourTable WHERE Ref NOT IN
(SELECT Ref FROM OtherTable WHERE Ref IS NOT NULL)
SELECT y.* FROM YourTable y
LEFT OUTER JOIN OtherTable o ON y.Ref = o.Ref
WHERE o.Ref IS NULL
另见Five ways to return all rows from one table which are not in another table
【讨论】:
试试这个:
SELECT * FROM TABLE WHERE NOT EXISTS
(SELECT * FROM OtherTable WHERE TABLE.Ref = OtherTable.ID)
【讨论】:
我认为这应该可行
SELECT * FROM table WHERE id NOT IN (SELECT ref_id FROM ref_table)
或与 JOIN
SELECT table.*
FROM table LEFT JOIN ref_table ON table.id = ref_table.ref_id
WHERE ref_table.ref_id IS NULL
【讨论】:
SELECT
table1.*
FROM
table1
LEFT JOIN table2 ON table1.id = table2.ref
WHERE
table2.ref IS NULL
【讨论】:
您可以执行如下子查询:
select * from table where somefield not in (select otherfield from sometable where ID=REF)
【讨论】:
SELECT *
FROM table
WHERE ((SELECT COUNT(*) FROM table2 WHERE table2.id = table.ref) = 0)
【讨论】:
类似的东西:
SELECT * FROM table WHERE ID NOT IN(SELECT REF FROM Table2 )
【讨论】:
是的,你可以使用
select * from x where not exist (select * from y)
【讨论】: