我想从mysql中选择数据。并且还希望在查询执行时进行一些计算。 我有两个sql表:
贷款表:
loan_id|Customer_name|Total_amount
1000 |Sashika |55000
1001 |Amell |11000
结算表:
Sett_id|Loan_id|Amount
a123 |1000 |1000
b123 |1001 |2000
这就是我的两张桌子的样子。 我想获得贷款的应有价值。我使用下面的代码生成,但它不会显示正确的值。
select loan.loan_id,loan.customer_name,loan.total_amount,sum(settlement.amount) as 'Total Received',
((loan.total_amount)-sum(settlement.amount ))as 'Total Due'
from loan , settlement
where loan.loan_id = 1001;
此代码获取settelement表的total(列)值。 当我尝试使用另一个贷款ID(其中loan_id =)时,还显示和计算结算价值总额。 但这不是我想要的价值。 请帮帮我们
Loan_ID| Customer_Name|Total_Amount|Total_Received|Total_Due
1000 |Sashika |55000 |1000 |54000
这就是我想要的 感谢您编辑我的问题并使其更易理解:)
答案 0 :(得分:1)
您应该使用内部联接和分组
select
loan.loan_id
,loan.customer_name
,loan.total_amount
,sum(settlement.amount) as 'Total Received'
,((loan.total_amount)-sum(settlement.amount ))as 'Total Due'
from loan
inner join settlement on loan.loan_id = settlement.loan_id
where loan.loan_id=1001
group by load.loan_id
答案 1 :(得分:0)
我会推荐这样的查询:
select l.*, (l.total_amount - s.amount) as amountDue
from loans l left join
(select loan_id, sum(amount) as amount
from settlement s
group by loan_id
) s
on l.loan_id = s.loan_id;
您的查询存在许多问题:
group by
。select
。join
语法的古老形式。简单规则:从不在from
子句中使用逗号。我还建议您不要对列别名使用单引号。 MySQL中正确的转义字符是反引号。仅对字符串和日期常量使用单引号。
答案 2 :(得分:0)
尝试,如果ID 1001没有结算,则内部联接不起作用,它将显示0行,显示收到的总数为null我已经改变了内部到左边的连接
select loan.loan_id, loan.customer_name, loan.total_amount,
sum(settlement.amount) as ''Total Received',
((loan.total_amount)-sum(settlement.amount )) as 'Total Due'
from load
left join settlement
on settlement.loan_id = loan.loan_id
where loan.loan_id = 1001;
答案 3 :(得分:0)
这是我的版本:
select
loan.loan_id,
loan.customer_name,
loan.total_amount,
ifnull(sum(settlement.amount), 0) as 'Total Received',
((loan.total_amount) - ifnull(sum(settlement.amount), 0)) as 'Total Due'
from loan
left join settlement on
settlement.loan_id = loan.loan_id
where
loan.loan_id=1000
您需要一个LEFT JOIN
,而不是内部联接来处理尚未付款的情况。
如果sum(settlement.amount)
表中没有条目,您还需要确保NULL
不返回settlement
,否则'总截止日期'也将是NULL
。
如果你一次只承担一次负担,你实际上并不需要像GROUP BY
这样的人。