▌刷题回顾


【SQL刷题系列】:leetcode178 Rank Scores


▌题目描述


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.

假设一个网站包含两个表: Customers和Orders。写出一个SQL查询语句找出所有没有任何订单的顾客。


Customers表:

+----+-------+| Id | Name  |+----+-------+| 1  | Joe   || 2  | Henry || 3  | Sam   || 4  | Max   |+----+-------+


Orders表:

+----+------------+| Id | CustomerId |+----+------------+| 1  | 3          || 2  | 1          |+----+------------+


使用上面两个表,你的查询结果应该与下面这样相同。

+-----------+| Customers |+-----------+| Henry     || Max       |+-----------+


▌参考答案


参考1:

select Name as Customers from Customers
where Id not in (select distinct CustomerId from Orders);


参考2:

select name AS Customers
from Customers LEFT JOIN Orders 
ON Customers.Id=Orders.CustomerId 
WHERE Orders.CustomerId IS NULL;


▌答案解析


参考1:通过查询select的嵌套使用。先在Orders表中返回所有有订单的客户Id,然后在Customer查询不在Orders表中的客户Id,最后返回相应的用户名字,即为最终结果。当然,也可以使用join通过连接两个表来实现


参考2:将Customers表的Id与Orders表的CustomerId建立左连接,那么Orders原本缺少的信息就会自动用NULL来代替。然后用where查询是NULL的用户名字即可。


©著作权归作者所有:来自51CTO博客作者mb5fe18e9fef50b的原创作品,如需转载,请注明出处,否则将追究法律责任

更多相关文章

  1. Python有序字典的两个小“惊喜”~~
  2. Python 为什么只需一条语句“a,b=b,a”,就能直接交换两个变量?
  3. 图解 LeetCode 第 421 题:数组中两个数的最大异或值
  4. LeetCode数据库篇|175组合两个表
  5. php中比较两个数组差异的方法
  6. PHP如何计算两个时间段交集的天数?
  7. PHP 框架 Hyperf 实现处理超时未支付订单和延时队列
  8. php如何计算两个时间戳之间相差的日时分秒

随机推荐

  1. 在创建多对多关系后,Sequelize Node.js新
  2. mysql批量删除相同前缀的表和修改表名
  3. MySql_数据库触发器的使用
  4. MySQL数据库root账户的设置和管理
  5. 版本5及更高版本中MySQL数据库的最大大小
  6. Mysql PARTITION 数据表分区技术
  7. mysql批量结束线程
  8. MySQL数据库表名、列名、别名区分大小写
  9. 在Google Cloud Platform上设计PolyGlot
  10. mysql存储过程调试记实