【问题标题】:SQL - How do I list rows from one table on the basis of them not appearing in another?SQL - 我如何列出一个表中的行,因为它们没有出现在另一个表中?
【发布时间】:2014-10-05 17:36:46
【问题描述】:

我有一个客户表(其中包含客户 ID 和姓氏)和一个订单表,并且必须列出未下订单即未出现在订单表中的客户的 ID 和姓名。我试过这个:

SELECT custID,familyname
FROM customers
WHERE custID = 
(SELECT custID
FROM orders
WHERE COUNT(custID)<1);

但出现错误。我必须使用不存在吗?还是不在?

【问题讨论】:

  • Theres also a LEFT JOIN b on..WHERE b.col IS NULL`

标签: mysql sql datatables


【解决方案1】:

你没有使用not exists。你应该想要:

SELECT c.custID, c.familyname
FROM customers
WHERE not exists (select 1 from orders o where o.custId = c.custId);

【讨论】:

    【解决方案2】:

    您还可以使用外连接并过滤那些没有匹配的实例:

    select c.custid, c.familyname
      from customers c
      left join orders o
        on c.custid = o.custid
     where o.custid is null
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-07
      • 2021-12-22
      • 2017-07-07
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 2011-05-11
      相关资源
      最近更新 更多