描述
如下有一张商品表(goods),字段依次为:商品id、商品名、商品质量
还有一张交易表(trans),字段依次为:交易id、商品id、这个商品购买个数
查找购买个数超过20,质量小于50的商品,按照商品id升序排序,如:
+------+------+--------+ | id | name | weight | +------+------+--------+ | 1 | A1 | 100 | | 2 | A2 | 20 | | 3 | B3 | 29 | | 4 | T1 | 60 | | 5 | G2 | 33 | | 6 | C0 | 55 | +------+------+--------+
还有一张交易表(trans),字段依次为:交易id、商品id、这个商品购买个数
+------+----------+-------+ | id | goods_id | count | +------+----------+-------+ | 1 | 3 | 10 | | 2 | 1 | 44 | | 3 | 6 | 9 | | 4 | 1 | 2 | | 5 | 2 | 65 | | 6 | 5 | 23 | | 7 | 3 | 20 | | 8 | 2 | 16 | | 9 | 4 | 5 | | 10 | 1 | 3 | +------+----------+-------+
查找购买个数超过20,质量小于50的商品,按照商品id升序排序,如:
+------+------+--------+-------+ | id | name | weight | total | +------+------+--------+-------+ | 2 | A2 | 20 | 81 | | 3 | B3 | 29 | 30 | | 5 | G2 | 33 | 23 | +------+------+--------+-------+
CREATE TABLE `goods` ( `id` int(11) NOT NULL, `name` varchar(10) DEFAULT NULL, `weight` int(11) NOT NULL, PRIMARY KEY (`id`) ); CREATE TABLE `trans` ( `id` int(11) NOT NULL, `goods_id` int(11) NOT NULL, `count` int(11) NOT NULL, PRIMARY KEY (`id`) ); insert into goods values(1,'A1',100); insert into goods values(2,'A2',20); insert into goods values(3,'B3',29); insert into goods values(4,'T1',60); insert into goods values(5,'G2',33); insert into goods values(6,'C0',55); insert into trans values(1,3,10); insert into trans values(2,1,44); insert into trans values(3,6,9); insert into trans values(4,1,2); insert into trans values(5,2,65); insert into trans values(6,5,23); insert into trans values(7,3,20); insert into trans values(8,2,16); insert into trans values(9,4,5); insert into trans values(10,1,3);
WITH trans_new AS (SELECT *, SUM(count) AS total FROM trans GROUP BY goods_id Having total > 20 ), goods_new AS (SELECT id, name, weight FROM goods WHERE weight < 50 ) SELECT g.id, g.name, g.weight, t.total FROM goods_new AS g LEFT JOIN trans_new AS t ON g.id = t.goods_id ORDER BY g.id;