题目
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 | +-----------+
第一反应是用count()<1 写着写着被自己这个智障的想法笑到
然后就想到了应该是用NOT EXIST语句
==要注意一下 是EXISTS
果然不自己动手打永远不能发现错误
SELECT Name AS Customers
FROM Customers
WHERE Id NOT EXISTS (SELECT Customers.Id FROM Customers C,Orders O WHERE C.Id=O.CustomerId)
运行结果说参数错误
看了大家分享的答案 发现把WHERE后面的Id去掉就正确了
可以看一下下面两个exists和in语句的区别
一个人分享的3个答案 大家的语句都写得好简洁啊
如果想要运行的快 大概是join语句比较好
SELECT A.Name from Customers A
WHERE NOT EXISTS (SELECT 1 FROM Orders B WHERE A.Id = B.CustomerId)
SELECT A.Name from Customers A
LEFT JOIN Orders B on a.Id = B.CustomerId
WHERE b.CustomerId is NULL
SELECT A.Name from Customers A
WHERE A.Id NOT IN (SELECT B.CustomerId from Orders B)
EXISTS和IN
exists : 强调的是是否返回结果集,不要求知道返回什么
in引导的子句只能返回一个字段