【发布时间】:2016-03-27 22:46:50
【问题描述】:
我有这张桌子:
CREATE TABLE `stock` (
`id` int(11) NOT NULL,
`p_id` int(11) NOT NULL,
`quantity` decimal(11,2) DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
还有这张桌子:
CREATE TABLE `products` (
`id` int(10) UNSIGNED NOT NULL,
`codf` bigint(20) UNSIGNED NOT NULL,
`ean` bigint(20) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
如何获得每种产品的 codf 和 ean 的总量
例如,如果我有这只股票
id | p_id | quantity |
1 | 1 | 1 |
2 | 2 | 2 |
3 | 1 | 3 |
4 | 3 | 4 |
以及那些产品:
id | codf | ean |
1 | 1 | 11 |
2 | 1 | 12 |
3 | 2 | 13 |
我需要得到
codf 1 = 6
codf 2 = 4
ean 11 = 4
ean 12 = 2
ean 13 = 4
所以我需要按不同的 codf 对数量分组求和,并按不同的 ean 对数量分组求和,ean 也是唯一的
现在我在 php 中执行此操作,选择所有行,左连接产品,然后使用数组对它们进行分组并获得最终数量,如下所示:
select s.quantity, p.codf,p.ean from stock s left join products p on p.id = s.p_id
我有这个 php:
while($r = mysqli_fetch_assoc($q)) {
$total[$r[ean]] += $r[quantity];
$total[$r[codf]] += $r[quantity];
}
并为每个产品显示我们的库存数量
codf = a number for similar products
ean = a unique number a product can have
但如果我能在 mysql 中做到这一点,它真的会帮助我
谢谢,如果我拼错了什么,对不起,英语不是我的主要语言:)
【问题讨论】: