sql 183. 从不订购的客户

某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。

Customers 表:

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

Orders 表:

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

例如给定上述表格,你的查询应返回:

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

select customers.name as Customers from customers left join  orders on customers.id=orders.customerid where orders.customerid is null

这个sql用了左连接 和 is null语法。

左连接的这种用法学习到了。如果右边的表没有满足on 后条件的值就会为null

下面贴一个左连接执行顺序的讲解

执行顺序:先执行on and条件,再执行where条件

具体是:首先根据on and条件过滤出满足条件的右侧表记录,然后根据关联字段,左侧表再与过滤出的右侧表记录进行连接,

满足关联字段相等,则返回左侧表和右侧表字段信息;若不满足,则返回左侧表字段信息,右侧表字段则显示NULL

连接出的结果则存入临时表中。最后where条件是对临时表中的数据进行过滤。

左连接:Left join,以左侧表为主,不管on条件是否满足条件,左侧表的所有记录都会返回。

换句说:on and后面的条件对左侧表没有过滤作用,即使加上对左侧表的过滤,也不起作用。

on后面的条件对右侧表的过滤起作用。where条件则对左连接后的临时表数据进行筛选。

以例子说明:

select * from A left join B

on A.ID = B.ID and B.NAME = '连接' and A.NAME = ‘左连接’

where NAME = '左连接'

on and后面的条件:B.NAME对B表有过滤作用,A.NAME对A表不起过滤作用

where后面的条件:则是对左连接出的临时表数据进行过滤

原文地址:https://www.cnblogs.com/wangshaowei/p/11074665.html