心得
這題要show出沒有訂過東西的客戶,所以可以使用LEFT JOIN
來關聯兩張表。
問題
Suppose that a website contains two tables, the
Customers
table and theOrders
table. Write a SQL query to find all customers who never order anything.Table:
Customers
.+----+-------+ | Id | Name | +----+-------+ | 1 | Joe | | 2 | Henry | | 3 | Sam | | 4 | Max | +----+-------+Table:
Orders
.+----+------------+ | Id | CustomerId | +----+------------+ | 1 | 3 | | 2 | 1 | +----+------------+Using the above tables as example, return the following:
+-----------+ | Customers | +-----------+ | Henry | | Max | +-----------+
答案
LEFT JOIN
# Write your MySQL query statement below SELECT a.Name AS Customers FROM Customers AS a LEFT JOIN Orders AS b ON a.Id = b.CustomerId WHERE b.CustomerId IS NULL
Sub Query
# Write your MySQL query statement below SELECT a.Name AS Customers FROM Customers AS a WHERE ( SELECT COUNT(1) FROM Orders AS z WHERE z.CustomerId = a.Id) = 0