51 - 从不订购的客户
题目
某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。
Customers 表:
+----+-------+ | Id | Name | +----+-------+ | 1 | Joe | | 2 | Henry | | 3 | Sam | | 4 | Max | +----+-------+
Orders 表:
+----+------------+ | Id | CustomerId | +----+------------+ | 1 | 3 | | 2 | 1 | +----+------------+
例如给定上述表格,你的查询应返回:
+-----------+ | Customers | +-----------+ | Henry | | Max | +-----------+
解答
Not in
不是很理解,建表的时候为啥要加一句if not exists
,因为如果不加,有表会报错。加了,有表也不报错,就以为它是存在的了。
Runtime: 227 ms, faster than 94.81% of MySQL online submissions forCustomers Who Never Order.
Memory Usage: N/A
官方题解似乎做麻烦了,外面的select选的只有customers这个表,好像就不用特别声明是customer.name
关键是not in
,能做到反选的感觉
去重
Runtime: 270 ms, faster than 51.76% of MySQL online submissions forCustomers Who Never Order.
Memory Usage: N/A
left join
Runtime: 258 ms, faster than 64.41% of MySQL online submissions forCustomers Who Never Order.
Memory Usage: N/A
没想到on后面还能写where
估计from
到where
都是一组的,意思是把a.id=b.customerId
相等的放在一起组成一张表。
where是跟着select的,再把其中id为null的挑出来,就是最终结果了。
Last updated
Was this helpful?