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       |
+-----------+

第一反应是用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引导的子句只能返回一个字段

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值