描述
如下有一张商品表(goods),字段依次为:商品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 | +------+------+--------+-------+
示例1
输入:
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);
复制输出:
2|A2|20|81 3|B3|29|30 5|G2|33|23
分享自己的解题思路
首先一般地元素的具体属性我会选择最后进行连接,像这道题商品质量,
然后分组统计各商品的出入货数量总和,这里需要用到分组函数GROUP BY
SELECT t1.goods_id , SUM(t1.count) as total FROM trans t1 GROUP BY t1.goods_id
根据商品id分组,这里要用SUM求和函数 ,不是 COUNT() ,COUNT() 是用来统计出现次数的,然后根据商品id和goods表进行内连接(INNER JOIN),如下
SELECT t2.id , t2.name , t2.weight , t3.total
from
(SELECT t1.goods_id , SUM(t1.count) as total FROM trans t1 GROUP BY t1.goods_id) as t3
INNER JOIN
goods t2
ON
t2.id = t3.goods_id
然后附上约束条件数超过20,质量小于50
SELECT t2.id , t2.name , t2.weight , t3.total
from
(SELECT t1.goods_id , SUM(t1.count) as total FROM trans t1 GROUP BY t1.goods_id) as t3
INNER JOIN
goods t2
ON
t2.id = t3.goods_id and
t2.weight < 50 and t3.total > 20
然后得出正确结果