topic:
A site contains two tables, Customers table and the Orders table. Write a SQL query to find all customers never ordered anything.
Customers table:
±—±------+
| Id | Name |
±—±------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
±—±------+
Orders 表:
± - ± ----------- +
| Id | the CustomerId |
± - ± + -----------
|. 1 |. 3 |
| 2 |. 1 |
± - ± - + ---------
example given in the table above, your query should return:
±----------+
| Customers |
±----------+
| Henry |
| Max |
±----------+
answer:
//通过左连接,去除null值
select c.Name as Costomers from Customers c left join Orders o on C.Id=o.CustomerId where o.CustomerId is null;
// 子查询,order表中有的恰是我们不需要的。
select Name as Costomers from Customers where Id not in(select CustomerId from Orders);