从不订购的客户
1、题目:
某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。
Customers 表:
+—-+——-+
| Id | Name |
+—-+——-+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
+—-+——-+
Orders 表:
+—-+————+
| Id | CustomerId |
+—-+————+
| 1 | 3 |
| 2 | 1 |
+—-+————+
例如给定上述表格,你的查询应返回:
+———–+
| Customers |
+———–+
| Henry |
| Max |
+———–+
2、解题步骤:
(1) 创建表:
CREATE TABLE `customers` (
`Id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Id',
`Name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '客户姓名',
PRIMARY KEY (`Id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '客户表' ROW_FORMAT = Dynamic;
CREATE TABLE `orders` (
`Id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Id',
`customerId` int(11) DEFAULT NULL COMMENT '客户Id',
PRIMARY KEY (`Id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '订单表' ROW_FORMAT = Dynamic;
(2) 插入数据:
INSERT INTO `customers` VALUES (1, 'Joe');
INSERT INTO `customers` VALUES (2, 'Henry');
INSERT INTO `customers` VALUES (3, 'Sam');
INSERT INTO `customers` VALUES (4, 'Max');
INSERT INTO `orders` VALUES (1, 3);
INSERT INTO `orders` VALUES (2, 1);
(3) 查询SQL:
a、方案一:数据量小的时候建议使用。
SELECT *
FROM customers
WHERE Id NOT IN (
SELECT customerId
FROM orders
);
b、方案二:数据量大的时候建议使用。
SELECT a.*
FROM customers a
LEFT JOIN orders b ON a.Id = b.customerId
WHERE b.customerId IS NULL;
(4) 运行结果: