LeetCode 183. 从不订购的客户【mysql】

浅浅的花香味﹌ 2022-12-20 02:27 203阅读 0赞

183. 从不订购的客户

题意:

某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。

Customers 表:

  1. +----+-------+
  2. | Id | Name |
  3. +----+-------+
  4. | 1 | Joe |
  5. | 2 | Henry |
  6. | 3 | Sam |
  7. | 4 | Max |
  8. +----+-------+

Orders 表:

  1. +----+------------+
  2. | Id | CustomerId |
  3. +----+------------+
  4. | 1 | 3 |
  5. | 2 | 1 |
  6. +----+------------+

例如给定上述表格,你的查询应返回:

  1. +-----------+
  2. | Customers |
  3. +-----------+
  4. | Henry |
  5. | Max |
  6. +-----------+

Code:

  1. # 方法一:通过子查询和in
  2. select name as Customers from customers where id not in(
  3. select customerid from orders
  4. );
  5. # 方法二:通过left join 将其连成一个表
  6. select Name as Customers from customers as a left join orders as b on
  7. a.id = b.customerid where b.id is null;

发表评论

表情:
评论列表 (有 0 条评论,203人围观)

还没有评论,来说两句吧...

相关阅读