【leetcode Database】183. Customers Who Never Order

忘是亡心i 2022-09-24 06:22 70阅读 0赞

题目:

Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything.

Table: Customers.

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

Table: Orders.

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

Using the above tables as example, return the following:

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

解析:本题可以用多重查询来做。先把Orders表中的CustomerId字段取出来,然后把Customers表中所有Id不在CustomerId字段中的名字取出来即可。代码如下:

  1. # Write your MySQL query statement below
  2. SELECT Name AS Customers FROM Customers WHERE Id NOT IN (SELECT CustomerId FROM Orders);

发表评论

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

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

相关阅读