Mysql query with multiple join

时间:2016-06-20 05:32:41

标签: mysql

I have the following tables and would like to get the result as follow

Table po
ID | Date
1  | 20-Jun-2016

Table podetails
ID | poid | itemcode | quantity
1  | 1    | SOAP123  | 100

Table poreceived
ID | poid | itemcode | quantity
1  | 1    | SOAP123  | 20
2  | 1    | SOAP123  | 60

Result should be:

PO | Date        | itemcode | quantity
1  | 20-Jun-2016 | SOAP123  | 80

What I have done is:

SELECT 
    po.id, podetails.itemcode, poreceived.quantity
FROM
    po
        LEFT JOIN
    podetails ON podetails.poid = po.id
        LEFT JOIN
    poreceived ON poreceived.poid = podetails.poid

But the result is not what I expected.

Any help would be appreciate it.

1 个答案:

答案 0 :(得分:2)

看起来您需要按poreceivedpoid表进行汇总。您可以使用子查询:

SELECT po.id, COALESCE(podetails.itemcode, 'NA'), COALESCE(t.quantity, 0)
FROM po
LEFT JOIN podetails
    ON podetails.poid = po.id
LEFT JOIN
(
    SELECT poid, itemcode, SUM(quantity) AS quantity
    FROM poreceived
    GROUP BY poid, itemcode
) t
    ON t.poid = podetails.poid AND t.itemcode = podetails.itemcode

除了聚合问题,您的查询策略看起来是正确的。我还在COALESCEpodetails表的列中添加了poreceived,以防来自po的ID与任何内容不匹配。