i have this table:
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;
and this table:
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;
how can i get total quantity for both codf and ean for each product
so for example if i have this stock
id | p_id | quantity |
1 | 1 | 1 |
2 | 2 | 2 |
3 | 1 | 3 |
4 | 3 | 4 |
and those products:
id | codf | ean |
1 | 1 | 11 |
2 | 1 | 12 |
3 | 2 | 13 |
i need to get
codf 1 = 6
codf 2 = 4
ean 11 = 4
ean 12 = 2
ean 13 = 4
so i need to sum quantity grouping by distinct codf and sum quantity grouping by distinct ean, ean is also unique
Now i do it in php, i select all rows, left join products and i use arrays to group them and get the final quantity like so:
select s.quantity, p.codf,p.ean from stock s left join products p on p.id = s.p_id
and i have this php:
while($r = mysqli_fetch_assoc($q)) {
$total[$r[ean]] += $r[quantity];
$total[$r[codf]] += $r[quantity];
}
and display for each product the quantity we have in stock
codf = a number for similar products
ean = a unique number a product can have
but it would really help me if i can do it in mysql
Thanks and sorry if i misspelled something, english is not my primary language :)
SELECT ce
, val
, SUM(quantity) total
FROM
( SELECT 'codf' ce, codf val, s.quantity FROM products p JOIN stock s ON s.p_id = p.id
UNION
SELECT 'ean' ce, ean, s.quantity FROM products p JOIN stock s ON s.p_id = p.id
) x
GROUP
BY ce, val;