2017-06-23 39 views
0

背景:MySQL的 - 如何獲得兩個的hasMany關聯的查詢的hasMany關聯的不同行的總和?

我有三個表,即生產,production_lines和操作。

的production_lines有一個名爲「PARENT_ID」列其以前的生產線的基準。 production_lines的深度應等於操作。

以下是它們之間的關係:

Production_lines has many (child) production_lines. 
Production_lines belongs to Production. 
Productions has many operations. 

問題:

我要創建一個使用操作的數量和總量出去選擇目的單一的選擇查詢。問題在於兒童生產線由於加入了操作表而被複制。我怎樣才能明確地得出兒童生產線的數量總和?

目前的解決方案:

SELECT 
    `ProductionLine`.`id`, 
    `ProductionLine`.`operation_number`, 
    COUNT(DISTINCT `Production.StockCode.Operations`.id) AS 'numberOfOperations', 
    # This is where the problem is: It sums up including the duplicated entries due to Operations table. 
    SUM(ChildrenProductionLines.dozen_quantity * 12 + ChildrenProductionLines.piece_quantity) AS 'quantityOut' 
FROM 
    `production_lines` AS `ProductionLine` 
LEFT OUTER JOIN `productions` AS `Production` 
    ON `ProductionLine`.`production_id` = `Production`.`id` 
LEFT OUTER JOIN `operations` AS `Production.Operations` 
    ON `Production.Operations`.`production_id` = `Production`.`id` 
LEFT OUTER JOIN `production_lines` AS `ChildrenProductionLines` 
    ON `ProductionLine`.`id` = `ChildrenProductionLines`.`parent_id` 
GROUP BY `ProductionLine`.`id` 
HAVING `operation_number` < `numberOfOperations` 
ORDER BY `id`; 
+0

嘗試'OUTER JOIN's搬進'WHERE ID IN(子查詢)'。或成'JOIN'用'GROUP BY'和'COUNT()'列... –

+0

在第一次測試,我很驚訝它的工作。但不幸的是,如果我試圖具有相同dozen_quantity兩個孩子的生產線,piece_quantity,然後將它們視爲相同,產生不準確的結果。 – Xegara

+0

子查詢是唯一的解決辦法? – Xegara

回答

0

嘗試是這樣的:

SELECT `id`, `operation_number`, `numberOfOperations`, 
     SUM(`dozen_quantity` * 12 + `piece_quantity`) AS `quantityOut` 
FROM `production_lines` 
LEFT JOIN (SELECT `P`.`id`, COUNT(`C`.`id`) AS `numberOfOperations` 
      FROM `productions` AS `P` 
      LEFT JOIN `operations` AS `O` ON `O`.`production_id` = `P`.`id` 
      LEFT JOIN `production_lines` AS `C` ON `P`.`id` = `C`.`parent_id` 
      GROUP BY `P`.`id` 
     ) AS `Q` ON `production_id` = `Q`.`id` 
WHERE `operation_number` < `numberOfOperations` 
ORDER BY `id`; 
+0

看起來像子查詢是真正的解決方案,如果有至少兩個的hasMany關聯。謝謝! – Xegara

相關問題