MySQL查询增强工会

时间:2018-09-19 11:28:09

标签: php mysql

我有此查询将用于报告,并且我有很多数据。 目前,这是我在UNION ALL上使用UNION的查询,因为我记得上一个我使用过UNION的项目是它不能统一所有数据,所以我不知道为什么使用了UNION ALL

SELECT `item_id`, NULL AS `ob`,SUM(`add`) AS `add` ,NULL AS `dam`,NULL AS `sold`,NULL AS `others`,NULL AS `ac`
          FROM (
            -- DELIVERED ITEMS
            SELECT si.`item_id`,SUM(sdi.`actual_pcs`) AS `add`
            FROM `store_inventory` si
            LEFT JOIN `store_delivery` sd
            ON sd.`store_id` = si.`store_id` AND DATE(sd.`dt_modified`) = '2018-09-01'
            AND sd.`status` = "DONE"
            LEFT JOIN `store_delivery_items` sdi
            ON sdi.`strd_id` = sd.`strd_id` AND sdi.`item_id` = si.`item_id`
            WHERE si.`store_id` = '4'
            GROUP BY si.`item_id`

            UNION ALL

            -- OVERRIDE ADD (ADD)
            SELECT si.`item_id`,SUM(oi.`qty`) AS `add`
            FROM `store_inventory` si
            LEFT JOIN `override` o
            ON o.`ref_id` = si.`store_id`
            AND o.`type` = "STORE"
            AND o.`action` = "ADD"
            AND DATE(o.`dt_created`) = '2018-09-01'
            LEFT JOIN `override_items` oi
            ON oi.`item_id` = si.`item_id`
            AND oi.`ovr_id` = o.`ovr_id`
            WHERE si.`store_id` = '4'
            GROUP BY si.`item_id`

            UNION ALL

            -- CANCELLED SALES (ADD)
            SELECT si.`item_id`,SUM(sai.`si_qty`) AS `add`
            FROM `store_inventory` si
            LEFT JOIN `sales` s
            ON s.`sales_store_id` = si.`store_id`
            AND s.`cancelled_by` IS NOT NULL
            AND DATE(s.`dt_cancelled`) = '2018-09-01'
            LEFT JOIN `sales_items` sai
            ON sai.`si_sales_id` = s.`sales_id`
            AND sai.`si_item_id` = si.`item_id`
            WHERE si.`store_id` = '4' 
            GROUP BY si.`item_id`

            UNION ALL

            -- PULLOUT REJECTED ADDED BACK TO STORE (ADD)
            SELECT si.`item_id`,SUM(poi.`poi_actual`) AS `add`
            FROM `store_inventory` si
            LEFT JOIN `pullout` p
            ON p.`pullout_reason` IN ("STORE TO DAMAGE","STORE TO WAREHOUSE")
            AND p.`pullout_status` IN ("REJECT","HEAD-REJECTED")
            AND DATE(p.`dt_modified`) = '2018-09-01'
            AND p.`pullout_from` = si.`store_id`
            LEFT JOIN `pullout_items` poi
            ON poi.`poi_item_id` = si.`item_id`
            AND poi.`poi_pullout_id` = p.`pullout_id`
            WHERE si.`store_id` = '4'
            GROUP BY si.`item_id`
          ) AS add_temp
          GROUP BY `item_id`

您可以看到我从我的商店库存物品中循环了所有表格,这只是一天的报告,因为我在php中进行日期范围的循环。我想知道是否可以进一步增强此查询。我在桌子上尝试了左联接,但没有运气。这是这种报告的正确查询吗?这只是我的查询顺便说一句。您仍然可以在我的openingbalance,damaged,sold,others语句中看到此SELECT查询。因此,我确实需要有关此长查询的建议。我已经将列的索引添加到表中以便更快地选择结果。

0 个答案:

没有答案