[英]MySQL Join AND SUM on Both Tables
I'm trying to join two tables and sum the results from both tables columns but I can't figure out.我正在尝试连接两个表并对两个表列的结果求和,但我无法弄清楚。 I'm doing it in Joomla.我在 Joomla 做这件事。
invoices table:发票表:
id ID | owner所有者 | amount数量 |
---|---|---|
1 1个 | 123 123 | 300.00 300.00 |
2 2个 | 123 123 | 125.00 125.00 |
3 3个 | 144 144 | 200.00 200.00 |
4 4个 | 166 166 | 155.00 155.00 |
expenses table:费用表:
id ID | owner所有者 | amount数量 |
---|---|---|
1 1个 | 123 123 | 10.00 10.00 |
2 2个 | 123 123 | 50.00 50.00 |
3 3个 | 144 144 | 50.00 50.00 |
results:结果:
owner所有者 | invoices发票 | expenses花费 |
---|---|---|
123 123 | 425.00 425.00 | 60.00 60.00 |
144 144 | 200.00 200.00 | 50.00 50.00 |
166 166 | 155.00 155.00 | 0.00 0.00 |
This should give you the expect results.这应该会给你预期的结果。 I do LEFT JOIN
for results from both tables.我对两个表的结果执行LEFT JOIN
。
SELECT l.`owner`, invoices, IFNULL(expenses,0) FROM
(
SELECT
`owner`, SUM(amount) AS invoices
FROM
invoices
GROUP BY
`owner`
) AS l LEFT JOIN (
SELECT
`owner`, SUM(amount) AS expenses
FROM
expenses
GROUP BY
`owner`
) AS r ON l.`owner` = r.`owner`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.