MYSQL项报告重复

时间:2018-01-30 04:29:53

标签: mysql mysqli

我想获得一份关于特定商店销售和交付商品的报告, 我在哪里使用项目ID和商店ID分组。当我执行以获得交付的股票。我得到了我想要的结果但是。当我left join销售表时,我交付的库存结果重复。检查以下查询。正如您可以阅读我的查询,您可以获得我的表格看起来像

首先我获取商店商品,然后join获取商品表以获取商品名称, 然后join存储表以获取商店名称,然后left join存储到交付表以完成对特定商店ID的交付,并left join再次传递给delivery_items以获得什么是具有特定delivery_id的项目是否已传递到该store_id。等等

SELECT s.`store_id`,s.`name` AS `store`,i.`item_id` AS `id`,i.`item_name` AS `fruit`,
sti.`qty` AS `current_stock`, IF(SUM(di.`qty`) IS NULL,0,SUM(di.`qty`)) AS `delivered_stock`
FROM `store_item` sti
LEFT JOIN `item` i
ON i.`item_id` = sti.`item_id`
JOIN `Store` s
ON s.`store_id` = sti.`store_id`
LEFT JOIN `delivery` d
ON d.`store_id` = s.`store_id`
LEFT JOIN `delivery_item` di
ON di.`delivery_id` = d.`delivery_id`
AND di.`item_id` = i.`item_id`
GROUP BY i.`item_id`,s.`store_id`
ORDER BY s.`store_id`,i.`item_id` ASC

这是第一个按照规定工作的查询 enter image description here

但是一旦我添加了销售表来获得已售出的股票。一切都重复。我的头已经疼了。我整天都试图在group条款中添加更多内容来解决这个问题,但我无法得到预期的结果。

这是添加了销售表的查询

SELECT s.`store_id`,s.`name` AS `store`,i.`item_id` AS `id`,i.`item_name` AS `fruit`,
sti.`qty` AS `current_stock`, IF(SUM(di.`qty`) IS NULL,0,SUM(di.`qty`)) AS `delivered_stock`
,IF(SUM(sli.`qty`) IS NULL,0,SUM(sli.`qty`)) AS `sold_stock`
FROM `store_item` sti
LEFT JOIN `item` i
ON i.`item_id` = sti.`item_id`
JOIN `Store` s
ON s.`store_id` = sti.`store_id`
LEFT JOIN `delivery` d
ON d.`store_id` = s.`store_id`
LEFT JOIN `delivery_item` di
ON di.`delivery_id` = d.`delivery_id`
AND di.`item_id` = i.`item_id`
LEFT JOIN `sale` sl
ON sl.`store_id` = s.`store_id`
LEFT JOIN `sale_item` sli
ON sli.`item_id` = i.`item_id`
AND sli.`sale_id` = sl.`sale_id`
GROUP BY i.`item_id`,s.`store_id`
ORDER BY s.`store_id`,i.`item_id` ASC

我得到了重复的结果 enter image description here 任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

我已经做了一些技巧来获得我需要的东西,

我刚刚使用UNION来获得理想的结果

SELECT MAX(currentStock) AS currentStock,MAX(delivered) AS delivered
FROM (
SELECT SUM(current_stock) AS currentStock,NULL AS delivered
FROM ...

UNION ALL

SELECT NULL AS currentStock,SUM(delivered) AS delivered
FROM ...
) as temp