我想用mysql遍历
goods_id
在
goods
表,然后查询
order_goods
基于全部的表
古德萨德
你能解决这个问题吗?
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.创建订单货物并插入表格
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.查询订单货物表
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语句?