具有GROUP CONCAT和LEFT JOIN的行的SUM

时间:2015-06-10 18:53:13

标签: mysql sum left-join concat

我有一个关于MySQL的问题。

我收到了以下表格:

Invoices
invoices_ordermapping
invoices_positions

发票:

id | userid | state
1, 10, 1

invoices_ordermapping

id | invoiceid | orderid
1, 1, Order12
2, 1, Order13

invoices_positions

id | invoiceid | value | text
1, 1, 21, Example
2, 1, 18.9, Example 2

现在我想将已分配的订单发送到发票(Order12,Order13)和总和(价值总和)。

这是我期望的结果:

Invoiceid | Orders | Sum
1, Order12, Order13, 39.9

我正在使用这个MySQL-Query:

SELECT group_concat(DISTINCT orderid ORDER BY orderid SEPARATOR ", ") AS orderid, 
       SUM(ip.total) as value
FROM tbl_invoices as a
LEFT JOIN tbl_invoices_ordermapping as oi ON oi.invoiceid = a.id 
LEFT JOIN tbl_invoices_positions as ip on ip.invoiceid = oi.invoiceid          
GROUP BY oi.invoiceid
ORDER BY oi.invoiceid

不幸的是我得到了这个结果:

Orderid: Order12, Order12, Order13, Order13
Value: 119.69999885559082

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

我认为您需要以下内容:

SELECT a.id AS InvoiceId, Orders, `Sum`
FROM Invoices as a
LEFT JOIN (SELECT invoiceid,
                  GROUP_CONCAT(DISTINCT orderid 
                               ORDER BY orderid SEPARATOR ', ') AS Orders
           FROM Invoices_ordermapping 
           GROUP BY invoiceid ) AS oi ON oi.invoiceid = a.id
LEFT JOIN (SELECT invoiceid, SUM(`value`) as `Sum`
           FROM Invoices_positions
           GROUP BY invoiceid) AS ip ON ip.invoiceid = a.id
ORDER BY a.id

您的查询的问题是LEFT JOIN重复Invoices_positions行,因此,SUM计算在表的相同行的多次出现时。

您需要先为Invoices_ordermappingInvoices_positions表执行聚合,然后加入Invoices表。

Fiddle Demo here