Skip to content
Advertisement

Unable to join from 3 different tables – MySql

I am struggling to understand if this query is possible. I have 3 tables, User, Account, Loan. 2 users are linked by an account, and any loans facilitated between the 2 of them gets linked to the account_id. However, when i want to show the data in a table, i want to show the borrowers name from the users table, and the loan details from the loan table. but it is referenced from the lenders_id in the account table.

Here is the ERD: enter image description here

A practical example would be that if you were a lender and wanted to go to the dashboard to see all the loans you have given out, but wanted to see the names of the borrower, and the principal amount, interest rate etc. and nothing really about the account.

I want the final table to look something like:

BorrwerName | PrincipalAmount | InterestRate | RepaymentDate | Relationship

What i have so far

SELECT user.first_name, user.last_name, loan.principal, loan.interest_rate, 
loan.repayment_date, account.relationship
FROM user
INNER JOIN account ON account.borrower_id = user.id
INNER JOIN loan ON loan.account_id = account.id

The issue here is that no where do i even reference the Lender_ID. which is the Variable i need to pass to query whose loans to show. Im very lost, any help would be great.

Advertisement

Answer

Just add where clause in your query:

SELECT user.first_name, user.last_name, loan.principal, loan.interest_rate, 
loan.repayment_date, account.relationship
FROM user
INNER JOIN account ON account.borrower_id = user.id
INNER JOIN loan ON loan.account_id = account.id
where account.lender_id = value_to_be_searched;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement