由于某些未知原因,查询将两个SUM字段相互相乘:
表格
products table
+----+--------+
| id | p_name |
+----+--------+
| 1 | name1 |
| 2 | name2 |
+----+--------+
warehouses table:
+----+------------+
| id | w_name |
+----+------------+
| 1 | warehouse1 |
| 2 | warehouse2 |
+----+------------+
intake table:
+--------------+------------+--------+
| warehouse_id | product_id | amount |
+--------------+------------+--------+
| 1 | 1 | 10 |
| 1 | 1 | 10 |
+--------------+------------+--------+
outtake table
+--------------+------------+--------+
| warehouse_id | product_id | amount |
+--------------+------------+--------+
| 1 | 1 | 5 |
| 1 | 1 | 5 |
+--------------+------------+--------+
查询
SELECT warehouses.w_name,
products.p_name,
Sum(intake.units_amout) AS intakeSum,
Sum(outtake.amount) AS outtakeSum
FROM (warehouses
INNER JOIN (products
INNER JOIN intake ON products.id = intake.product_id) ON warehouses.id = intake.warehouse_id)
INNER JOIN outtake ON (warehouses.id = outtake.warehouse_id)
AND (products.id = outtake.product_id)
GROUP BY warehouses.w_name,
products.p_name;
结果
+--------------+------------+-----------+------------+
| warehouse_id | product_id | intakeSum | outtakeSum |
+--------------+------------+-----------+------------+
| 1 | 1 | 40 | 20 |
+--------------+------------+-----------+------------+
预期结果
+--------------+------------+-----------+------------+
| warehouse_id | product_id | intakeSum | outtakeSum |
+--------------+------------+-----------+------------+
| 1 | 1 | 20 | 10 |
+--------------+------------+-----------+------------+
如果我添加第三个入口(使用相同的产品和仓库ID),“outtakeSum”将乘以3!等等..
答案 0 :(得分:1)
这是因为如果使用输出表进入连接将导致总共四行导致总和为4 * 10 = 40和4 * 5 = 20。
为了解决这个问题,你可以做两个子查询,一个用于入口和出口表,每个子表将为每个warehouse_id / product_id对汇总这些表。
即:
SELECT warehouse_id, product_id, SUM(amount)
FROM intake
GROUP BY warehouse_id, product_id;
(和出口表的类似查询)
如果您使用这些查询而不是摄入量和加入时,它将按预期工作。