SQL105. 列出供应商及其可供产品的数量
描述
vend_id |
a0002 |
a0013 |
a0003 |
a0010 |
vend_id | prod_id |
a0001 | egg |
a0002 | prod_id_iphone |
a00113 | prod_id_tea |
a0003 | prod_id_vivo phone |
a0010 | prod_id_huawei phone |
vend_id | prod_id |
a0002 | 1 |
a0013 | 0 |
a0003 | 1 |
a0010 | 1 |
示例1
输入:
DROP TABLE IF EXISTS `Vendors`; CREATE TABLE IF NOT EXISTS `Vendors` ( `vend_id` VARCHAR(255) NOT NULL COMMENT 'vend名称' ); INSERT INTO `Vendors` VALUES ('a0002'), ('a0013'), ('a0003'), ('a0010'); DROP TABLE IF EXISTS `Products`; CREATE TABLE IF NOT EXISTS `Products` ( `vend_id` VARCHAR(255) NOT NULL COMMENT '产品 ID', `prod_id` VARCHAR(255) NOT NULL COMMENT '产品名称' ); INSERT INTO `Products` VALUES ('a0001','egg'), ('a0002','prod_id_iphone'), ('a00113','prod_id_tea'), ('a0003','prod_id_vivo phone'), ('a0010','prod_id_huawei phone');
输出:
a0002|1 a0003|1 a0010|1 a0013|0
Mysql 解法, 执行用时: 39ms, 内存消耗: 6460KB, 提交时间: 2022-03-04
select a.vend_id, count(b.prod_id) prod_id from Vendors a left join Products b using(vend_id) group by a.vend_id order by a.vend_id asc
Mysql 解法, 执行用时: 39ms, 内存消耗: 6528KB, 提交时间: 2022-03-07
SELECT A.vend_id,COUNT(B.prod_id) FROM Vendors AS A LEFT JOIN Products AS B ON A.vend_id = B.vend_id GROUP BY A.vend_id ORDER BY A.vend_id
Mysql 解法, 执行用时: 39ms, 内存消耗: 6528KB, 提交时间: 2022-03-07
select V.vend_id, count(if(prod_id is null, null, prod_id)) prod_id from Products P right join Vendors V on V.vend_id = P.vend_id group by vend_id order by vend_id
Mysql 解法, 执行用时: 40ms, 内存消耗: 6440KB, 提交时间: 2022-03-07
select a.vend_id vend_id,count(prod_id) prod_id from Vendors a left join Products b using(vend_id) group by a.vend_id order by vend_id
Mysql 解法, 执行用时: 40ms, 内存消耗: 6444KB, 提交时间: 2022-04-02
select a.vend_id,count(b.vend_id) as prod_id from Vendors a left join Products b on a.vend_id=b.vend_id group by a.vend_id order by vend_id;