简体   繁体   中英

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

I have 2 tables, borrowers and loans. 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.

(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.)

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.

(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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