标题8:MySQL-Duplicate Emails
题目8:MySQL----------Duplicate Emails
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 | +-----------+
题目解答:
SELECT A.Name from Customers A WHERE A.Id NOT IN (SELECT B.CustomerId from Orders B)
另外还可以写成下面两种方式:
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
- 3楼mchdba昨天 22:31
- mysqlu0026gt; CREATE TABLE Customers SELECT 1 AS id,u0026#39;Joeu0026#39; AS NAME UNION ALL SELECT 2,u0026#39;Henryu0026#39; UNION ALL SELECT 3,u0026#39;Samu0026#39; UNION ALL SELECT 4,u0026#39;Maxu0026#39;;nQuery OK, 4 rows affected (0.24 sec)nRecords: 4 Duplicates: 0 Warnings: 0nnmysqlu0026gt;nmysqlu0026gt; select * from Customers;n+----+-------+n| id | NAME |n+----+-------+n| 1 | Joe |n| 2 | Henry |n| 3 | Sam |n| 4 | Max |n+----+-------+n4 rows in set (0.02 sec)nnmysqlu0026gt; nmysqlu0026gt; CREATE TABLE Orders SELECT 1 AS id,3 AS CustomerId UNION ALL SELECT 2,1;nQuery OK, 2 rows affected (0.08 sec)nRecords: 2 Duplicates: 0 Warnings: 0nnmysqlu0026gt;nnmysqlu0026gt; select * from Orders;n+----+------------+n| id | CustomerId |n+----+------------+n| 1 | 3 |n| 2 | 1 |n+----+------------+n2 rows in set (0.00 sec)nnmysqlu0026gt;
- 2楼mchdba昨天 22:31
- mysqlu0026gt; SELECT A.Name FROM Customers A n -u0026gt; LEFT JOIN Orders B ON a.Id = B.CustomerId n -u0026gt; WHERE b.CustomerId IS NULL ;nERROR 1054 (42S22): Unknown column u0026#39;b.CustomerIdu0026#39; in u0026#39;where clauseu0026#39;nmysqlu0026gt; nn为什么报错?n对了,是表的别名区分大小写了,所以执行报错了。
- 1楼mchdba昨天 22:31
- 写成:nmysqlu0026gt; SELECT A.Name FROM Customers A n -u0026gt; LEFT JOIN Orders B ON A.Id = B.CustomerId n -u0026gt; WHERE B.CustomerId IS NULL ;n+-------+n| Name |n+-------+n| Henry |n| Max |n+-------+n2 rows in set (0.04 sec)nnmysqlu0026gt; nn就OK了。