I'm quite new in PHP/MySQL and I need to sum resuts of multiple queries grouped.
For example, I have a table like this:
Toy | Material 1 | Qt Mat 1 | Material 2 | Qt Mat 2 | Material 3 | Qt Mat 3
House | Wood | 2 kg | Cloth | 1 kg | Rubber | 0.5 kg
Horse | Wood | 3 kg | Rubber | 2 kg | |
Plane | Plastic | 1 kg | Steel | 2 kg | Rubber | 0.2 kg
Doll | Cloth | 2 kg | | | |
Car | Rubber | 1 kg | Plastic | 2 kg | |
Let's suppose that I want to build a House
, a Doll
and a Car
.
My shopping list would be:
Wood - 2 kg (House)
Cloth - 3 kg (1 for House, 2 for Doll)
Rubber - 1.5 kg (0.5 for House, 1 for Car)
Plastic - 2 kg (Car)
How can I generate this using PHP and MySQL?
SELECT Material,SUM(Qty) as NetQty
FROM (
SELECT Material1 as Material, QtMat1 as Qty
FROM tableName
WHERE Toy IN ('House','Doll','Car')
UNION ALL
SELECT Material2, QtMat2
FROM tableName
WHERE Toy IN ('House','Doll','Car')
UNION ALL
SELECT Material3, QtMat3
FROM tableName
WHERE Toy IN ('House','Doll','Car')
) As qry
GROUP BY qry.Material
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.