【问题标题】:Opposite Of An Inner Join Query与内部联接查询相反
【发布时间】:2011-05-01 23:44:55
【问题描述】:

有人可以帮我为这样的场景编写 sql:

Table 1

2 columns: ID, Name

Table 2

2 columns: ID, Name

我想要一个查询来显示表 1 中不在表 2 中的名称。因此,过滤掉表 1 中表 2 中的所有名称是结果查询。使用 ID 进行过滤而不是名称。

这将对我正在尝试做的事情有所帮助。提前致谢

【问题讨论】:

  • 尼克,下面的所有建议(那些使用连接并检查 null 以及建议使用 NOT IN 子句的建议)都将起作用。但是,如果速度是一个问题,我相信 NOT IN 会更慢。如果速度不是问题,那么 NOT IN 可能更清晰。
  • INNER JOIN 的对立面是 OUTER JOIN,它有两种风格:LEFT 和 RIGHT,具体取决于您想要“outer”的 JOIN 的哪一侧
  • @Matt:你的想法是错误的,NOT IN 更快。
  • 你说得对@Quassnoi。我花了一段时间才得到足够大的时间和数据集来测量它,但即使是查询执行计划也显示 NOT IN 大约快 50%。我不知道谁告诉我这个肮脏的谎言摆在首位! :)

标签: sql-server tsql inner-join outer-join


【解决方案1】:
Select * from table1
left join table2 on table1.id = table2.id
where table2.id is null

【讨论】:

【解决方案2】:

这应该比left join...is null 版本执行得更好。请参阅herehere 进行比较。

select t1.id, t1.name
    from table1 t1
    where not exists(select null from table2 t2 where t2.id = t1.id)

【讨论】:

  • @Eduardo Cuomo:不在 SQL Server 中。
【解决方案3】:

使用这个查询

select
t1.*
from table1 t1
left outer join table2 t2
on t1.id=t2.id
where t2.id is null

这是通过将 t1 中的所有内容连接到 t2 中存在的所有内容来实现的。 where 子句过滤掉所有不存在于 t2 中的记录。

【讨论】:

    【解决方案4】:
    SELECT Table1.ID, Table1.Name, Table2.ID 
    FROM Table1 LEFT OUTER JOIN Table2 ON Table1.ID = Table2.ID 
    WHERE Table2.ID IS NULL 
    

    我认为应该这样做。

    【讨论】:

      【解决方案5】:

      试试这样:

      select t1.*
      from table1 as t1
      where t1.id not in 
        (select distinct t2.id from table2 as t2);
      

      【讨论】:

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