【问题标题】:Subquery with multiple select statements具有多个选择语句的子查询
【发布时间】:2011-05-21 09:59:11
【问题描述】:

检查在“不在”条件下具有多个选择语句的子查询

例如。

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 'not in' 条件,该子查询将从多个表中一次检查..

请帮忙..

【问题讨论】:

  • 您看似紧迫的问题已在下方得到解答.....

标签: sql subquery correlated-subquery


【解决方案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

【讨论】:

  • (重新编号您的表格,因为您两次加入 table1,而根本没有加入 table3)
【解决方案2】:

你可以使用联合,所以你只有一个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 在此处不可为空。

【讨论】:

    【解决方案3】:

    全部使用联合 像这样 --> select f.FIRST_NAME from farmer f where f.ID in (select v.ID from Village v where v.ID in (1,2) union all select s.ID from state s where s.ID in (3,4) )

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-03
      相关资源
      最近更新 更多