SQL实现LeetCode(183.从未下单订购的顾客)
[leetcode] 183.customers who never order 从未下单订购的顾客
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.
+----+-------+
| 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 |
+-----------+
这道题让我们给了我们一个customers表和一个orders表,让我们找到从来没有下单的顾客,那么我们最直接的方法就是找没有在orders表中出现的顾客id就行了,用not in关键字,如下所示:
解法一:
select name as customers from customers where id not in (select customerid from orders);
或者我们也可以用左交来联合两个表,只要找出右边的customerid为null的顾客就是木有下单的:
解法二:
select name as customers from customers left join orders on customers.id = orders.customerid where orders.customerid is null;
我们还可以用not exists关键字来做,原理和not in很像,参见代码如下:
解法三:
select name as customers from customers c where not exists (select * from orders o where o.customerid = c.id);
参考资料:
到此这篇关于sql实现leetcode(182.从未下单订购的顾客)的文章就介绍到这了,更多相关sql实现从未下单订购的顾客内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!