SQL95. 从 Products 表中检索所有的产品名称以及对应的销售总数
描述
prod_id | prod_name |
a0001 | egg |
a0002 | sockets |
a0013 | coffee |
a0003 | cola |
prod_id | quantity |
a0001 | 105 |
a0002 | 1100 |
a0002 | 200 |
a0013 | 1121 |
a0003 | 10 |
a0003 | 19 |
a0003 | 5 |
prod_name | quant_sold |
egg | 105 |
sockets | 1300 |
coffee | 1121 |
cola | 34 |
示例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'); DROP TABLE IF EXISTS `OrderItems`; CREATE TABLE IF NOT EXISTS `OrderItems`( prod_id VARCHAR(255) NOT NULL COMMENT '产品id', quantity INT(16) NOT NULL COMMENT '商品数量' ); INSERT `OrderItems` VALUES ('a0001',105),('a0002',1100),('a0002',200),('a0013',1121),('a0003',10),('a0003',19),('a0003',5);
输出:
egg|105.000 sockets|1300.000 coffee|1121.000 cola|34.000
Mysql 解法, 执行用时: 39ms, 内存消耗: 6576KB, 提交时间: 2022-03-08
SELECT a.prod_name, SUM(b.quantity) FROM Products a, OrderItems b WHERE a.prod_id = b.prod_id GROUP BY a.prod_name
Mysql 解法, 执行用时: 39ms, 内存消耗: 6596KB, 提交时间: 2022-03-04
select prod_name,sum(quantity) as quant_sold from (select t1.prod_name,t2.quantity from Products t1,OrderItems t2 where t1.prod_id=t2.prod_id) t group by prod_name
Mysql 解法, 执行用时: 40ms, 内存消耗: 6436KB, 提交时间: 2022-06-05
select prod_name, quant_sold from Products, (select prod_id,sum(quantity) as quant_sold from OrderItems group by prod_id) as temp where Products.prod_id=temp.prod_id;
Mysql 解法, 执行用时: 40ms, 内存消耗: 6444KB, 提交时间: 2022-03-06
select prod_name,(select sum(quantity) from OrderItems where OrderItems.prod_id=Products.prod_id group by prod_id) as quant_sold from Products
Mysql 解法, 执行用时: 40ms, 内存消耗: 6472KB, 提交时间: 2022-03-04
SELECT prod_name, SUM(quantity) as quant_sold FROM Products INNER JOIN OrderItems USING(prod_id) GROUP BY prod_name