从 1 Table 中选择没有出现在另一个 Table 中的记录

Selecting Records From 1 Table That Don't Appear In Another Table

我希望有人可以帮助我解决我遇到的这个问题。 我有一个 table 客户 - 我们称之为 Table C。我还有第二个 table 客户不被称为 - 我们称之为 Table D。

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

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

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

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

使用 NOT EXISTS 执行此操作:

SELECT c.*
FROM tableC c
WHERE NOT EXISTS (
        SELECT *
        FROM tableD d
        WHERE c.customerID = d.customerid
        );
Select * from table.c where customer_id not in (select distinct customer_id from table.d);

如果您想使用联接,那么它是您想要的左联接,并在 d table 中对空值进行筛选。正确的连接会让你得到 d table 中的所有行,加上 c table 中的匹配行 - 与你想要的完全相反,但是如果你切换了 table 左右然后你会得到相同的结果,所以这个:

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 值),因为我认为这些更清楚地传达了意图。