我想使用mysql遍历goods_id
表中的所有goods
,然后根据所有order_goods
查询goods_id
表中每一行的总和。您能解决这个问题吗?
1。创建商品表并插入表
CREATE TABLE `goods` (
`goods_id` int(11) NOT NULL,
`goods_name` varchar(255) NOT NULL,
PRIMARY KEY (`goods_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `goods` (`goods_id`, `goods_name`) VALUES
(1, 'Apple'),
(2, 'Xiaomi'),
(3, 'Huawei');
2。创建order_goods并插入表格
CREATE TABLE `order_goods` (
`id` int(11) NOT NULL,
`order_id` int(11) NOT NULL,
`goods_id` int(11) NOT NULL,
`goods_name` varchar(255) NOT NULL,
`goods_num` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `order_goods` (`id`, `order_id`, `goods_id`, `goods_name`,
`goods_num`) VALUES
(1, 1, 1, 'iPhone X', 2),
(2, 2, 1, 'iPhone 8 plus', 1),
(3, 3, 2, 'Y69A', 1),
(4, 4, 2, 'X21', 3),
(5, 5, 3, 'nova 3', 1),
(6, 6, 3, 'P20 Pro', 3),
(7, 7, 3, 'Mate 10 Pro', 5);
3。查询商品表
mysql> select * from goods;
+----------+------------+
| goods_id | goods_name |
+----------+------------+
| 1 | Apple |
| 2 | Xiaomi |
| 3 | Huawei |
+----------+------------+
3 rows in set (0.00 sec)
4。查询order_goods表
mysql> select * from order_goods;
+----+----------+----------+---------------+-----------+
| id | order_id | goods_id | goods_name | goods_num |
+----+----------+----------+---------------+-----------+
| 1 | 1 | 1 | iPhone X | 2 |
| 2 | 2 | 1 | iPhone 8 plus | 1 |
| 3 | 3 | 2 | Y69A | 1 |
| 4 | 4 | 2 | X21 | 3 |
| 5 | 5 | 3 | nova 3 | 1 |
| 6 | 6 | 3 | P20 Pro | 3 |
| 7 | 7 | 3 | Mate 10 Pro | 5 |
+----+----------+----------+---------------+-----------+
7 rows in set (0.00 sec)
5。我想尝试获得这种效果!
+----+----------+----------+---------------+
| id | goods_id | goods_name | num |
+----+----------+----------+---------------+
| 1 | 1 | Apple | 3 |
| 2 | 2 | Xiaomi | 4 |
| 3 | 3 | Huawei | 9 |
+----+----------+----------+---------------+
例如,写sum(g.goods_num) as num
如何编写上面的sql语句?
答案 0 :(得分:2)
X
是您进行分组以包含SUM()
的查询
然后,您将其与goods
一起加入,以获取名称和ID以及此表中您需要的任何内容
这样的表现可能会更好,因为首先进行分组
WITH X AS
(
SELECT goods_id,SUM(goods_num) AS num
FROM order_goods
GROUP BY goods_id
)
SELECT G.goods_name , X.num
FROM X
INNER JOIN goods G ON G.goods_id = X.goods_id
没有WITH
子句,因此将联接加入查询
像这样:
SELECT goods_id,SUM(goods_num) AS num
FROM order_goods OG
INNER JOIN goods G ON G.goods_id = OG.goods_id
GROUP BY OG.goods_id -- or G.goods_name
答案 1 :(得分:1)
对分组依据使用内部联接和聚合:
http://sqlfiddle.com/#!9/ae4fd9/3
select go.goods_id,g.goods_name,sum(goods_num) as num
from goods g inner join order_goods go
on g.goods_id=go.goods_id
group by g.goods_name,go.goods_id
输出:
goods_id goods_name num
1 Apple 3
3 Huawei 9
2 Xiaomi 4
答案 2 :(得分:1)
goods_id
在两个表之间进行INNER JOIN。goods_id
子句在GROUP BY
中进行grouping。num
。尝试以下查询:
SELECT g.goods_id,
g.goods_name,
SUM(og.goods_num) AS num
FROM goods g
JOIN order_goods og ON og.goods_id = g.goods_id
GROUP BY g.goods_id, g.goods_name