我有两个mysql表:
table: loan
--------------------------------------------------------
id | advance_id | loan_amount | deposit_amount | date
--------------------------------------------------------
1 | 22556678 | 5000 | 0 | 2015-02-06
2 | 22556678 | 5000 | 0 | 2015-02-07
--------------------------------------------------------
table: advance
--------------------------------------------------------
id | advance_id | advance_amount | purpose | date
--------------------------------------------------------
1 | 22556678 | 20000 | purchase | 2015-01-30
2 | 22556678 | 10000 | purchase | 2015-01-31
我希望获得贷款金额的总和'从表:贷款和' advance_amount' from table:在INNER JOIN加入的一个mysql查询中前进。
如何从两个表的列中获取总和?
SELECT
a.advance_id,
SUM(a.advance_amount) AS adv_amount,
a.purpose,
a.date,
SUM(l.loan_amount) AS loan_amount
FROM
advance AS a
INNER JOIN loan AS l
ON a.advance_id = l.advance_id
GROUP BY a.advance_id
HAVING SUM(l.loan_amount) - SUM(l.deposit_amount) > 0
答案 0 :(得分:2)
您可以将查询重写为
SELECT
a.advance_id,
SUM(a.advance_amount) AS adv_amount,
a.purpose,
a.date,
l.loan_amount
FROM
advance AS a
INNER JOIN
(
SELECT advance_id,SUM(deposit_amount) AS loan_amount
FROM loan
GROUP BY advance_id
HAVING SUM(loan_amount) - SUM(deposit_amount) > 0
) AS l USING(advance_id)
GROUP BY a.advance_id