SQL104. 返回产品名称和每一项产品的总订单数
描述
prod_id | prod_name |
a0001 | egg |
a0002 | sockets |
a0013 | coffee |
a0003 | cola |
a0023 | soda |
prod_id | order_num |
a0001 | a105 |
a0002 | a1100 |
a0002 | a200 |
a0013 | a1121 |
a0003 | a10 |
a0003 | a19 |
a0003 | a5 |
prod_name | orders |
coffee | 1 |
cola | 3 |
egg | 1 |
sockets | 2 |
soda | 0 |
示例1
输入:
DROP TABLE IF EXISTS `Products`; CREATE TABLE IF NOT EXISTS `Products` ( `prod_id` VARCHAR(255) NOT NULL COMMENT '产品 ID', `prod_name` VARCHAR(255) NOT NULL COMMENT '产品名称' ); INSERT INTO `Products` VALUES ('a0001','egg'), ('a0002','sockets'), ('a0013','coffee'), ('a0003','cola'), ('a0023','soda'); 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 ('a0001','a105'),('a0002','a1100'),('a0002','a200'),('a0013','a1121'),('a0003','a10'),('a0003','a19'),('a0003','a5');
输出:
coffee|1 cola|3 egg|1 sockets|2 soda|0
Mysql 解法, 执行用时: 39ms, 内存消耗: 6616KB, 提交时间: 2022-03-04
select prod_name,ifnull(aa.cnt,0) from Products left join ( select prod_id,count(*) cnt from OrderItems group by prod_id )aa on aa.prod_id=Products.prod_id order by prod_name
Mysql 解法, 执行用时: 40ms, 内存消耗: 6420KB, 提交时间: 2022-04-02
select prod_name,count(order_num) as orders from Products left join OrderItems using(prod_id) group by prod_name order by prod_name
Mysql 解法, 执行用时: 40ms, 内存消耗: 6440KB, 提交时间: 2022-08-05
select p.prod_name,count(o.order_num) as orders from Products p left join OrderItems o on p.prod_id = o.prod_id group by p.prod_name order by p.prod_name
Mysql 解法, 执行用时: 40ms, 内存消耗: 6444KB, 提交时间: 2022-07-21
select prod_name,count(order_num) as orders from Products left join OrderItems using(prod_id) group by prod_name order by prod_name
Mysql 解法, 执行用时: 40ms, 内存消耗: 6444KB, 提交时间: 2022-04-18
select prod_name ,count(o.order_num) as orders from Products p left join OrderItems o on p.prod_id = o.prod_id group by p.prod_name order by p.prod_name