2018-10-30
183.Customers Who Never Order
文章目录
一、Description:
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 |
+-----------+
二、Solution:
解法一:
#Approach I: Using sub-query and NOT IN clause [Accepted]
select name as Customers
from customers
where id not in (select customerid from orders)
解法二:
#Approach II: Did a left join to find the null values and then filtered to them
SELECT Name AS 'Customers'
FROM Customers c
LEFT JOIN Orders o
ON c.Id = o.CustomerId
WHERE o.CustomerId IS NULL
解法三:
#Approach III: not exists to them
select Name from Customers c
where not exists
(select CustomerId from Orders o where c.Id=o.CustomerId);
三、总结知识点:
1、NOT IN
WHERE 子句中的 NOT 操作符有且只有一个功能,那就是否定其后所跟的任何条件。因为 NOT 从不单独使用(它总是与其他操作符一起使用),所以它的语法与其他操作符有所不同。 NOT 关键字可以用在要过滤的列前,而不仅是在其后。
为什么使用 NOT ?对于简单的 WHERE 子句,使用 NOT 确实没有什么优势。但在更复杂的子句中, NOT 是非常有用的。例如,在与 IN 操作符联合使用时, NOT 可以非常简单地找出与条件列表不匹配的行。
说明: MariaDB 中的 NOT
MariaDB 支持使用 NOT 否定 IN 、 BETWEEN 和 EXISTS 子句。大多数 DBMS 允许使用 NOT 否定任何条件。
2、IS NULL
空值检查
在创建表时,表设计人员可以指定其中的列能否不包含值。在一个列不包含值时,称其包含空值 NULL 。
NULL
无值( no value ),它与字段包含 0 、空字符串或仅仅包含空格不同。
确定值是否为 NULL ,不能简单地检查是否 = NULL 。 SELECT 语句有一个特殊的 WHERE 子句,可用来检查具有 NULL 值的列。这个 WHERE 子句就是 IS NULL 子句。其语法如下:
SELECT prod_name
FROM Products
WHERE prod_price IS NULL;
这条语句返回所有没有价格(空 prod_price 字段,不是价格为 0 )的产品。
警告: NULL 和非匹配
通过过滤选择不包含指定值的所有行时,你可能希望返回含 NULL 值的行。但是这做不到。因为未知( unknown )有特殊的含义,数据库不知道它们是否匹配,所以在进行匹配过滤或非匹配过滤时,不会返回这些结果。