mysql连接三个表

时间:2015-12-02 21:30:29

标签: mysql sql left-join

another question类似的问题,除了我所拥有的三个表是分层的而不是两个并排的表。

我有的表是

我的顶级客户表

id | name
1  | alan
2  | bob
3  | charlie

我的二级发票表

id | client_id | paid
1  | 1         | 0
2  | 1         | 1
3  | 2         | 1

我的第三级服务表

id | invoice_id | amount
1  | 1          | 5.00
2  | 1          | 10.00
3  | 2          | 5.00
4  | 3          | 10.00

我希望的结果是

id | name    | amount_owing | amount_paid
1  | alan    | 15.00        | 5.00
2  | bob     | null         | 10.00
3  | charlie | null         | null

我可以得到一些不考虑是否有报酬的东西

SELECT
    clients.email,
    jnt.*
FROM clients
LEFT JOIN (
    SELECT 
        invoices.client_id,
        SUM(amount) AS invoice_total_paid
    FROM
        invoices,
        services
    WHERE 
        invoices.id = services.invoice_id 
    GROUP BY
        invoices.client_id
) AS jnt ON clients.id = jnt.client_id

给了我

id | name    | client_id | invoice_total
1  | alan    | 1         | 20.00
2  | bob     | 2         | 10.00
3  | charlie | 3         | null

但它不会分担是否支付发票(以及随后的付款和欠款)。任何帮助非常感谢

2 个答案:

答案 0 :(得分:3)

您可以使用条件聚合获得预期结果:

SELECT c.id, c.name,
       SUM(CASE WHEN i.paid = 0 THEN s.amount ELSE 0 END) AS amount_owing,
       SUM(CASE WHEN i.paid = 1 THEN s.amount ELSE 0 END) AS amount_paid
FROM clients AS c
LEFT JOIN invoices AS i ON c.id = i.client_id
LEFT JOIN services AS s ON i.id = s.invoice_id
GROUP BY c.id, c.name

Demo here

答案 1 :(得分:0)

你需要像

这样的东西
...
SUM(IF(paid=1,amount,0)) AS amount_paid,
SUM(IF(paid=0,0,amount)) AS amount_owning
...