我在sql select查询中得到了错误的记录

时间:2016-06-13 08:21:37

标签: mysql

我想从MySQL中选择数据。并且还想在查询执行时进行一些计算。我有两个SQL表:

贷款表:

loan_id|Customer_name|Total_amount|Collector
1000   |Sashika      |55000       |Kapoor
1001   |Amell        |11000       |Kapoor
1002   |Oliver       |15000       |Kapoor

结算表:

Sett_id|Loan_id|Amount
a123    |1000    |1000
b123    |1000    |1000

特别想要点 1001& 1002贷款尚未收到任何结算。我想选择贷款按收集者名称。并选择应该是这样的:

输出表

Loan_ID| Customer_Name|Total_Amount|Total_Received|Total_Due
1000   |Sashika       |55000       |2000          |53000
1001   |Amell         |11000       |0             |11000
1002   |Oliver        |15000       |0             |15000

为此,我使用下面的选择查询。但它只显示1000(loan_id)记录。 我认为因为只有1000(loan_id)有结算记录。 1001& 1002没有任何记录,这就是它没有显示的原因。但我的要求是加载所有贷款详情,如上面的输出表

目前我使用以下代码:

select
loan.loan_id as 'Loan ID'
   ,loan.customer_name as 'Customer Name'
   ,loan.total_amount as 'Total Amount'
   ,ifnull(sum(settlement.amount),0) as 'Total Received'
   ,((loan.total_amount)-ifnull(sum(settlement.amount), 0))as 'Total Due'
from loan
inner join settlement  on  loan.loan_id =  settlement.loan_id
where loan.collector_name='kapoor'
group by loan.loan_id

就像我说的那样,它没有显示1001,1002(loan_id)的记录,如输出表

3 个答案:

答案 0 :(得分:1)

在这种情况下,上述两个表之间需要左连接。

select
 loan.loan_id AS 'Loan ID',
 loan.customer_name AS 'Customer Name',
 loan.total_amount AS '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 loan.loan_id = settlement.loan_id
WHERE
    loan.collector_name = 'kapoor'
GROUP BY    loan.loan_id

答案 1 :(得分:0)

INNER JOIN永远不会显示在结算表中找不到的loan_ids。使用LEFT JOIN

答案 2 :(得分:0)

您需要起诉LEFT JOIN以返回您想要的数据,因为loan_id 10011002不存在结算表。

同样在表格结构中,您在当前使用collector的代码中说collector_name,在我的下面的代码和SQL Fiddle示例中,我使用了collector

SELECT 
l.loan_id AS 'Loan ID',
l.customer_name AS 'Customer Name',
l.total_amount AS 'Total Amount',
IFNULL(SUM(s.amount),0) AS 'Total Received',
((l.total_amount) - IFNULL(SUM(s.amount), 0)) AS 'Total Due'
FROM loan l
LEFT JOIN settlement s on l.loan_id =  s.loan_id
WHERE l.collector_name = 'kapoor'
GROUP BY l.loan_id

输出:

loan_id Customer_name   Total_amount    Total Received  Total Due
1000    Sashika         55000           2000            53000
1001    Amell           11000           0               11000
1002    Oliver          15000           0               15000

SQL小提琴:http://sqlfiddle.com/#!9/fe704/2/0