【问题标题】:Selecting Records From 1 Table That Don't Appear In Another Table从 1 个表中选择未出现在另一个表中的记录
【发布时间】:2015-11-08 05:07:12
【问题描述】:

我希望有人能够帮助我解决我遇到的这个问题。 我有一张客户表 - 我们称之为 C 表。我还有第二张不被调用的客户表 - 我们称之为 D 表。

我想从表 C 中提取所有需要的信息(姓名、地址、电话等),除非客户出现在表 D 中。

在下面显示的示例中,我希望返回除 John Doe(ID:1)和 Fred Savage(ID:5)之外的所有客户的数据

我认为RIGHT OUTER JOIN 可能适用于此,但我之前没有使用过这种类型的连接。

【问题讨论】:

  • 您的研究是否出现EXCEPT,或者在您使用的 SQL Server 版本中不可用?

标签: sql-server tsql join right-join


【解决方案1】:

使用NOT EXISTS 执行此操作:

SELECT c.*
FROM tableC c
WHERE NOT EXISTS (
        SELECT *
        FROM tableD d
        WHERE c.customerID = d.customerid
        );

【讨论】:

  • 谢谢 - 在子查询中使用“Select *”而不是使用 select D.CustomerID 是否会影响性能,因为这基本上就是我要检查的全部内容?
  • 老实说,NOT EXISTS 完全适合您的场景类型。据我了解,select * 不会对性能造成影响,因为子查询中有 where 子句。您可以将其更改为Select customerid,看看您是否发现任何性能提升。
【解决方案2】:

如果您想使用连接,那么它是您想要的左连接,并带有 d 表中的空值过滤器。正确的连接会让你得到 d 表中的所有行,加上 c 表中的匹配行 - 与你想要的完全相反,但如果你切换了表,那么你会得到相同的结果,所以这个:

select c.* from c
left join d on c.CustomerID = d.CustomerID
where d.CustomerID is null

相当于:

select c.* from d
right join c on c.CustomerID = d.CustomerID
where d.CustomerID is null;

我个人更喜欢使用相关的not exists 查询或not in(但要注意null 值),因为我认为它们更清楚地传达了意图。

【讨论】:

  • 感谢您花时间提供帮助 - 我最终使用了 NOT EXISTS 代码 - 这些字段是 ID,不应为 NULL。
  • @MISNole 我也会使用not exists。 :) 为了清楚起见,我只是想使用连接添加一个答案。
【解决方案3】:
Select * from table.c where customer_id not in (select distinct customer_id from table.d);

【讨论】:

  • 这可能适用于这种情况,但在查询中使用NOT IN 时必须小心。 The most important thing to note about NOT EXISTS and NOT IN is that, unlike EXISTS and IN, they are not equivalent in all cases. Specifically, when NULLs are involved they will return different results. To be totally specific, when the subquery returns even one null, NOT IN will not match any rows.
  • @FutbolFan 是的。
【解决方案4】:

是的,您想要一个外部联接。 试试这个:https://technet.microsoft.com/en-US/library/ms187518(v=SQL.105).aspx

【讨论】:

猜你喜欢
  • 2022-01-21
  • 1970-01-01
  • 2015-08-27
  • 1970-01-01
  • 2021-01-26
  • 2020-10-08
  • 1970-01-01
  • 2012-10-29
  • 2013-05-19
相关资源
最近更新 更多