mysql 连接三个表
mysql join across three tables
与 another question 类似的问题,除了我的三个 table 是分层的,而不是并排的两个 table。
我的table是
我的顶级客户table
id | name
1 | alan
2 | bob
3 | charlie
我的二级发票table
id | client_id | paid
1 | 1 | 0
2 | 1 | 1
3 | 2 | 1
还有我的 3 级服务 table
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
但它不区分发票是否已支付(以及随后的支付和欠款总额)。非常感谢任何帮助
您可以使用条件聚合获得预期结果:
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
你需要这样的东西
...
SUM(IF(paid=1,amount,0)) AS amount_paid,
SUM(IF(paid=0,0,amount)) AS amount_owning
...
与 another question 类似的问题,除了我的三个 table 是分层的,而不是并排的两个 table。
我的table是
我的顶级客户table
id | name
1 | alan
2 | bob
3 | charlie
我的二级发票table
id | client_id | paid
1 | 1 | 0
2 | 1 | 1
3 | 2 | 1
还有我的 3 级服务 table
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
但它不区分发票是否已支付(以及随后的支付和欠款总额)。非常感谢任何帮助
您可以使用条件聚合获得预期结果:
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
你需要这样的东西
...
SUM(IF(paid=1,amount,0)) AS amount_paid,
SUM(IF(paid=0,0,amount)) AS amount_owning
...