在空时获取数据在SQL中找到表

时间:2014-05-10 16:18:30

标签: mysql sql

我正在创建这个贷款申请,我有两个主要的表,loans_request表和loans_account表,当申请贷款时,申请的工作方式是这样的它保存在loans_request表格中,当它已获得批准并付款时,付款会存储在loans_account表格中。

我创建了一个如下所示的SQL:

 SELECT  lr.RequestId,
    lr.SapNumber,
    lr.AmountRequested,
    lr.InterestRate,
    lr.AmountRequested * lr.InterestRate /100 +lr.AmountRequested AS AmountDue,
    lr.AmountRequested * lr.InterestRate /100 AS Interest,
    lr.DateDue,
    IFNULL(SUM(la.LoanAmount), 0) AS AmountPaid,
    (lr.AmountRequested * lr.InterestRate /100 +lr.AmountRequested) - SUM(la.LoanAmount) AS Debt,
    members.FirstName,
    members.Surname,
    members.OtherNames,
    la.SoftDelete
FROM loans_account la
INNER JOIN loans_request lr
ON la.LoanRequestId = lr.RequestId
INNER JOIN members
ON lr.SapNumber = members.SapNumber
WHERE lr.SoftDelete <> '1'
AND la.SoftDelete <> '1'
AND lr.Approved = '1'
AND lr.PaymentComplete = '0'
GROUP BY la.LoanRequestId;

此代码的问题是,当发出贷款请求时,因为没有对loans_account表进行任何付款,它会返回一个空的结果,因此意味着没有未偿还的贷款债务。

我希望代码告诉我,如果特定贷款满足所有where clauses,则不会对特定贷款进行任何付款,我希望仅在la.SoftDelete&lt;&gt;时才计算债务1,因为这意味着在la.SoftDelete = 1时已经还原了付款。

我希望我的问题足够有建设性,我会很感激所有答案。

谢谢

1 个答案:

答案 0 :(得分:0)

where条件移至case中的select语句:

 SELECT  lr.RequestId,
    lr.SapNumber,
    lr.AmountRequested,
    lr.InterestRate,
    lr.AmountRequested * lr.InterestRate /100 +lr.AmountRequested AS AmountDue,
    lr.AmountRequested * lr.InterestRate /100 AS Interest,
    lr.DateDue,
    IFNULL(SUM(la.LoanAmount), 0) AS AmountPaid,
    (lr.AmountRequested * lr.InterestRate /100 +lr.AmountRequested) - SUM(la.LoanAmount) AS Debt,
    members.FirstName,
    members.Surname,
    members.OtherNames,
    la.SoftDelete,
    (case when lr.SoftDelete <> '1' AND la.SoftDelete <> '1' AND lr.Approved = '1' AND lr.PaymentComplete = '0'
          then 'None' else 'Some'
     end) as Outstanding
FROM loans_account la INNER JOIN
     loans_request lr
     ON la.LoanRequestId = lr.RequestId INNER JOIN
     members
     ON lr.SapNumber = members.SapNumber
GROUP BY la.LoanRequestId;

注意:这假设联接不会过滤您想要的行。如果是,则需要left outer join并将逻辑切换为:

    (case when lr.SoftDelete = '1' OR la.SoftDelete = '1' OR lr.Approved <> '1' OR lr.PaymentComplete = '0'
          then 'Some'
          else 'None'
     end) as Outstanding
FROM loans_account la LEFT JOIN
     loans_request lr
     ON la.LoanRequestId = lr.RequestId LEFT JOIN
     members
     ON lr.SapNumber = members.SapNumber;

(我改变了逻辑,因此非匹配将进入none类别。)