SQL99. 返回购买 prod_id 为 BR01 的产品的所有顾客的电子邮件(二)
描述
prod_id | order_num |
BR01 | a0001 |
BR01 | a0002 |
BR02 | a0003 |
BR02 | a0013 |
order_num | cust_id | order_date |
a0001 | cust10 | 2022-01-01 00:00:00 |
a0002 | cust1 | 2022-01-01 00:01:00 |
a0003 | cust1 | 2022-01-02 00:00:00 |
a0013 | cust2 | 2022-01-01 00:20:00 |
cust_id | cust_email |
cust10 | cust10@cust.com |
cust1 | cust1@cust.com |
cust2 |
cust2@cust.com |
cust_email |
cust10@cust.com |
cust1@cust.com |
示例1
输入:
DROP TABLE IF EXISTS `OrderItems`; CREATE TABLE IF NOT EXISTS `OrderItems`( prod_id VARCHAR(255) NOT NULL COMMENT '产品id', order_num VARCHAR(255) NOT NULL COMMENT '商品订单号' ); INSERT `OrderItems` VALUES ('BR01','a0001'),('BR01','a0002'),('BR02','a0003'),('BR02','a0013'); DROP TABLE IF EXISTS `Orders`; CREATE TABLE IF NOT EXISTS `Orders`( order_num VARCHAR(255) NOT NULL COMMENT '商品订单号', cust_id VARCHAR(255) NOT NULL COMMENT '顾客id', order_date TIMESTAMP NOT NULL COMMENT '下单时间' ); INSERT `Orders` VALUES ('a0001','cust10','2022-01-01 00:00:00'),('a0002','cust1','2022-01-01 00:01:00'),('a0003','cust1','2022-01-02 00:00:00'),('a0013','cust2','2022-01-01 00:20:00'); DROP TABLE IF EXISTS `Customers`; CREATE TABLE IF NOT EXISTS `Customers`( cust_id VARCHAR(255) NOT NULL COMMENT '顾客id', cust_email VARCHAR(255) NOT NULL COMMENT '顾客email' ); INSERT `Customers` VALUES ('cust10','cust10@cust.com'),('cust1','cust1@cust.com'),('cust2','cust2@cust.com');
输出:
cust10@cust.com cust1@cust.com
Mysql 解法, 执行用时: 38ms, 内存消耗: 6436KB, 提交时间: 2022-03-07
select cust_email from OrderItems join Orders using(order_num) join Customers using(cust_id) where prod_id='BR01'
Mysql 解法, 执行用时: 39ms, 内存消耗: 6460KB, 提交时间: 2022-03-06
select c.cust_email from Orders o left join OrderItems oi on o.order_num=oi.order_num left join Customers c on o.cust_id=c.cust_id where oi.prod_id='BR01'
Mysql 解法, 执行用时: 39ms, 内存消耗: 6540KB, 提交时间: 2022-03-03
select cust_email from Orders join Customers using (cust_id) join OrderItems using (order_num) where prod_id="BR01"
Mysql 解法, 执行用时: 40ms, 内存消耗: 6452KB, 提交时间: 2022-03-02
SELECT cust_email FROM Orders o JOIN OrderItems i USING(order_num) JOIN Customers c USING(cust_id) WHERE prod_id = 'BR01'
Mysql 解法, 执行用时: 40ms, 内存消耗: 6472KB, 提交时间: 2022-03-07
select cust_email from OrderItems a inner join Orders b on a.order_num=b.order_num inner join Customers c on b.cust_id=c.cust_id where prod_id='BR01'