多个查询的求和结果

时间:2014-04-07 04:54:42

标签: php mysql sql

我是PHP / MySQL的新手,我需要对多个查询的重新组合进行求和。

例如,我有一个这样的表:

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   |            |

我们假设我要构建HouseDollCar。 我的购物清单是:

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) 

如何使用PHP和MySQL生成它?

1 个答案:

答案 0 :(得分:0)

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