【问题标题】:MySQL- Compare Customer IDs from two tables to determine who made no purchasesMySQL-比较两个表中的客户 ID 以确定谁没有购买
【发布时间】:2019-04-16 23:46:47
【问题描述】:

我在 SQL 中有两张表,一张包含有关客户和他们所下订单的信息(列包括 customerid、contactname、orderid、quantity 等等)。我的第二个表只是所有客户 ID 的列表,我的任务是确定哪个客户 ID 没有进行购买。一些客户 ID 进行了多次购买,所以我不确定如何使用 SELECT DISTINCT 来比较这两个表。

【问题讨论】:

  • 您能添加一些示例数据吗?
  • 客户 ID|公司名称|联系人姓名|联系人职务|地址|城市|地区|邮政编码|国家|电话|传真|订单号|订单日期|必需日期|发货日期| EmployeeID|Freight($)|ProductID|UnitPrice($)|Quantity|Discount(%) VINET|Vins et alcools Chevalier|Paul Henriot|会计经理| 59 rue de l'Abbaye|兰斯| NULL|51100|法国|26.47.15.10|26.47.15.11|10248| 2016-07-04| 2016-08-01| 2016-07-16|5|32.38|11| 14.00| 12| 0
  • 抱歉格式过于苛刻。这都是标题行和一行数据的示例。
  • 您好,如果您可以在问题中添加两个表格,那就更好了。所以任何人都能够正确理解这个问题,并且可以给你一个明确的答案。在不了解更多信息的情况下无法确定如何识别购买

标签: mysql sql select distinct


【解决方案1】:

加入第二个表并过滤结果

    SELECT DISTINCT t1.customerid, t1.contactname
    FROM table1 t1
    JOIN table2 t2
    ON t1.customerid = t2.customerid
    WHERE t1.customerid = t2.customerid

【讨论】:

    【解决方案2】:

    使用not exists:

    select t2.customerid
    from table2 t2
    where not exists (select 1 from table1 t1 where t1.customerid = t2.customerid);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-10
      • 2015-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多