【sql】统计没有预约的客户 Customers Who Never Order

问题:web

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.spa

Table: Customers.code

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+

Table: Orders.it

+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+

Using the above tables as example, return the following:table

+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+

① 使用NOT IN,找没有在Orders表中出现的顾客Id。769 mstab

SELECT Name AS Customers FROM Customers 
WHERE Id NOT IN (SELECT CustomerId FROM Orders);query

② 使用NOT EXISTS。795 msco

SELECT Name AS Customers FROM Customers c
WHERE NOT EXISTS (SELECT * FROM Orders o WHERE o.CustomerId = c.Id);return

SELECT Name AS Customers FROM Customers c
WHERE NOT EXISTS(SELECT CustomerId FROM Orders o WHERE c.Id = o.CustomerId);ab

③ 用左交来联合两个表,只要找出右边的CustomerId为Null的顾客就是没有下单的。795ms

SELECT Name AS Customers 
FROM Customers c LEFT JOIN Orders o ON c.Id = o.CustomerId
WHERE o.CustomerId IS NULL;  

相关文章
相关标签/搜索