简体   繁体   English

左连接 - Select ALL 来自左表,但 select 仅来自右表的最新

[英]Left Join - Select ALL from left table but select only the latest from right table

I have 2 tables, borrowers and loans.我有 2 张桌子,借款人和贷款。 I want to display on the main page the list of ALL borrowers with or without loans.我想在主页上显示所有有或没有贷款的借款人的列表。 If with loan, display the newest one.如果有贷款,显示最新的。

I have the following sql query, basically it returns the above description except it displays the very first loan of the borrower instead of the latest one.我有以下 sql 查询,基本上它返回上述描述,除了它显示借款人的第一笔贷款而不是最新贷款。

(Side note: I used GROUP BY to avoid duplicates. Without it the query returns duplicated borrower names if they have multiple loans. Just wanted to know if this is an efficient way of doing so.) (旁注:我使用 GROUP BY 来避免重复。没有它,如果有多个贷款,查询会返回重复的借款人姓名。只是想知道这是否是一种有效的方法。)

SELECT b.b_id, 
       b.isdeleted, 
       b.picture, 
       b.firstname, 
       b.middlename, 
       b.lastname, 
       b.address, 
       b.contactno,
       b.birthday, 
       b.businessname, 
       b.occupation, 
       b.comaker, 
       b.comakerno, 
       b.remarks, 
       b.datecreated, 
       b.activeloan,
       l.l_id, 
       l.amount, 
       l.payable, 
       l.balance, 
       l.mode, 
       l.term, 
       l.interestrate, 
       l.amortization,
       l.releasedate, 
       l.duedate, 
       l.status, 
       l.c_id
FROM borrowers as b
LEFT JOIN loans as l ON b.b_id = l.b_id
WHERE b.isdeleted = 0
GROUP BY b.b_id

It seems the below query does exactly what i wanted.看来下面的查询正是我想要的。

I added the below subquery on the "ON" clause.我在“ON”子句中添加了以下子查询。

(SELECT MAX(l_id)
 FROM jai_db.loans as l2
 WHERE l2.b_id = b.b_id LIMIT 1)
SELECT b.b_id, b.isdeleted, b.picture, b.firstname, b.middlename, b.lastname, b.address, b.contactno,
                                    b.birthday, b.businessname, b.occupation, b.comaker, b.comakerno, b.remarks, b.datecreated, b.activeloan,
                                    l.l_id, l.amount, l.payable, l.balance, l.mode, l.term, l.interestrate, l.amortization,
                                    l.releasedate, l.duedate, l.status, l.c_id
                             FROM jai_db.borrowers as b
                             LEFT JOIN jai_db.loans as l
                             ON l.l_id = (SELECT MAX(l_id)
                                          FROM jai_db.loans as l2
                                          WHERE l2.b_id = b.b_id LIMIT 1) 
                             WHERE b.isdeleted = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM