具有多个select语句的子查询

时间:2011-05-21 09:59:11

标签: sql subquery correlated-subquery

检查在'not in'条件

内有多个select语句的子查询

例如

select id from tbl where 
id not in (select id from table1) and 
id not in (select id from table2) and
id not in (select id from table3)

而不是重复相同的id'不在'条件,我需要子查询,它将从多个表中一次检查..

请帮助..

3 个答案:

答案 0 :(得分:1)

您的查询更好地表达为:

SELECT id 
FROM tbl t
LEFT JOIN table1 t1 on t1.id = t.id 
LEFT JOIN table2 t2 on t2.id = t.id 
LEFT JOIN table3 t3 on t3.id = t.id 
WHERE t1.id IS NULL AND t2.id IS NULL AND t3.id IS NULL

答案 1 :(得分:0)

你可以使用联盟,所以你只有一个in

select  id
from    tbl 
where   id not in 
        (
        select id from table1
        union all select id from table2
        union all select id from table3
        )

注意:not in无法使用可空列,但我认为此处id不可为空。

答案 2 :(得分:0)

使用union all 像这样 - > 从农民f中选择f.FIRST_NAME,其中f.ID在(从村庄v中选择v.ID,其中v.ID在(1,2)联合中所有选择s.ID来自状态s,其中s.ID在(3,4))

相关问题