如何在选择中选择

时间:2009-04-17 15:42:33

标签: sql

我有一个包含唯一ID字段的表。另一个字段(REF)包含对另一个数据集的ID字段的引用。 现在我必须选择REF指向不存在的数据集的所有数据集。

SELECT * FROM table WHERE ("no dataset with ID=REF exists")

我该怎么做?

8 个答案:

答案 0 :(得分:21)

3种方式

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

答案 1 :(得分:6)

试试这个:

SELECT * FROM TABLE WHERE NOT EXISTS 
     (SELECT * FROM OtherTable WHERE TABLE.Ref = OtherTable.ID)

答案 2 :(得分:5)

我认为这应该有用

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

答案 3 :(得分:4)

SELECT 
 table1.* 
FROM 
 table1
 LEFT JOIN table2 ON table1.id = table2.ref
WHERE 
 table2.ref IS NULL

答案 4 :(得分:3)

您可以执行以下子查询:

select * from table where somefield not in (select otherfield from sometable where ID=REF)

答案 5 :(得分:1)

SELECT * 
FROM table 
WHERE ((SELECT COUNT(*) FROM table2 WHERE table2.id = table.ref) = 0)

答案 6 :(得分:1)

类似的东西:

SELECT * FROM table WHERE ID NOT IN(SELECT REF FROM Table2 )

答案 7 :(得分:0)

是的,你可以使用

从x中选择*不存在(从y中选择*)