Unable to join from 3 different tables - MySql - 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:
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.

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;

You can add a WHERE clause:
SELECT u.first_name, u.last_name, l.principal, l.interest_rate,
l.repayment_date, a.relationship
FROM user u JOIN
account a
ON a.borrower_id = u.id JOIN
loan l
ON l.account_id = a.id
WHERE a.lender_id = ?;
You don't need to SELECT the column to filter on it.

Related

Join two tables query

I have two tables users and linkage. I am creating a link between one user to another. Means user A will be linked to user B and vise versa.
Now I want to get the details of linked users for a particular entered user_id. Means If user A is finding his linked Id's then the details of linked id's should be seen.
Linkage has three columns its id, user_id and linked_contact_id.
Users has columns as user_id, user_name,pass etc..
I tried one join but I only get the linked Id's from this not the details of id's.
SELECT * FROM Users INNER JOIN linkage ON linkage.user_id = Users.user_id WHERE linkage.linked_contact_id = 1
output
user_id linked_contact_id
1 4
1 1
1 5
How can I get this?Please help.. Thank you...
You will need to join on the users table a second time:
SELECT u.*, u2.* FROM Users u
INNER JOIN linkage l ON l.user_id = u.user_id
INNER JOIN Users u2 ON l.linked_contact_id = u2.user_id
WHERE l.linked_contact_id = 1
Please note that as you are selecting the same columns twice (in u.*, u2.*), you will probably have to list out each field with an alias to distinguish between them.
Something wrong on your ratio. But it's okay.
Try LEFT JOIN or RIGHT JOIN
SELECT * users
LEFT JOIN linkage
ON linkage.user_id = users.user_id
WHERE linkage.linked_contact_id = 1
Get Users information
SELECT users.*,
linkage.*,
contact.user_id as contact_user_id,
contact.user_name AS contact_user_name
FROM users
INNER JOIN linkage ON linkage.user_id = users.user_id
INNER JOIN users AS contact ON linkage.linked_contact_id = contact.user_id
WHERE linkage.linked_contact_id = 1
Edit
Here Screenshot of Query Output

MySQL using Group By to limit results

Okay, so I am trying to perform a query that has 4 tables,
users, events, event_roles, user_event_role.
The users can fill multiple roles. What i am trying to do is get a result that looks more like this:
User, event, Role(s)
So if user 'Bill' is associated with event 'Meeting' and 'Bill' Fills multiple roles instead of getting a result like this:
user event role
--------------------------
bill Meeting admin
bill Meeting director
how would I get my result to be like this
user event role role
----------------------------------
bill Meeting admin director
Here is a query that I'm trying to build off of.
Select *
FROM `users` u
LEFT JOIN `event_role` er ON u.user_id = er.user_id
LEFT JOIN `events` e ON er.event_id = e.event_id
The result you seek is not possible.
However there is something close:
SELECT
user,
event,
group_concat(role SEPARATOR ',') as roles
FROM
`users` u
LEFT JOIN `event_role` er
ON u.user_id = er.user_id
LEFT JOIN `events` e
ON er.event_id = e.event_id
GROUP BY u.user_id
which would yield:
user event roles
----------------------
bill Meeting admin,director
In either case you would need to adjust your logic to parse it correctly.
You cannot get such result, because you don't know how many roles there might be (i.e. columns count), but you can use GROUP_CONCAT that way:
SELECT *,
GROUP_CONCAT(event_roles.role SEPARATOR ',') as roles
FROM users
LEFT JOIN event_role USING(user_id)
LEFT JOIN events USING(user_id)
GROUP BY user_id
Using this query you will get all roles concatonated with ,. But be aware of limitation of GROUP_CONCAT, the default value is set to 1024 characters which might not be enough (see my.cnf).
Use Group_concat (http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html) like this.
To show that quickly, I'm using a database from the excellent MySQL intro book by Ben Forta (http://www.forta.com/books/0672327120/), no affiliation.
SELECT v.vend_id, GROUP_CONCAT(p.prod_id)
FROM products p
JOIN vendors v ON v.vend_id= p.vend_id
JOIN orderitems oi ON oi.prod_id = p.prod_id
GROUP BY v.vend_id;

Hybrid Left/Right Join based on condition?

I'm trying to write an SQL statement to retrieve a list of users from a database, along side their company name (if they have a company associated with them). However, there are a couple gotchas:
Not all users have companies, but I still need to show these people in the list.
Even if a user has a company, that company could be soft-deleted (the record is still in the database, but is flagged with is_deleted = 1), and I don't want to show users that are associated with "deleted" companies.
So essentially I want to SELECT from the User table and LEFT JOIN the company table, but I don't want to include the User record at all if the company they are assigned to is_deleted.
My first inclination is that I would have to use a UNION to merge two queries together, but I was hoping there would be a cleaner way to do it?
Using Mysql 5.1
SELECT U.name Username, C.name Company
FROM User U
LEFT OUTER JOIN Company C
ON U.companyid = C.id
WHERE C.id IS NULL OR C.is_deleted = 0
C.id IS NULL gets the users with no company, and C.is_deleted = 0 gets the users with companies that haven't been soft-deleted.
Try joining to a table that excludes the deleted companies:
SELECT U.Name, C.Name
FROM User U LEFT OUTER JOIN
(SELECT CompanyId, CompanyName
FROM Company
WHERE is_deleted = 0)
C ON U.CompanyId = C.CompanyId

MySQL SQL command to query from one table with three same columns to another table

Sorry but I am not sure how to ask this question but I am working on a help desk application where I have tickets being created in one table. I also have another table that stores the users. My problem is with the tickets table, I have listed the user that created the ticket, the tech who will solve the ticket and a user that over sees the ticket. All three users reference the users table. So how do I can I query the tickets table and get all three users that reference the same table storing the users?
Table1: Tickets
1) Ticketnumber
2) EnteredBy User 100
3) Issue
4) FixedBy User 102
5) FixedByNotes
6) ResponsilbeUser User 103
Table2: Users
1) UserID
2) UserName
What I can do now is something like this:
Select Ticketnumber, EnteredBy, Issue, UserName FROM Tickets INNER JOIN Users
ON Tickets.EnteredBy = Users.UserID
Thanks Steve
You can extend current query to somewhat as follows:
Select Ticketnumber, Issue, Reporter.UserName, Developer.UserName, Manager.UserName FROM Tickets
INNER JOIN Users AS Reporter ON Tickets.EnteredBy = Reporter.UserID
INNER JOIN Users AS Developer ON Tickets.FixedBy = Developer.UserID
INNER JOIN Users AS Manager ON Tickets.ResponsibleUser = Manager.UserID
You need alias for joint tables if you want to get all names:
Select Ticketnumber, Issue, Informers.UserName, Fixers.UserName, Supervisors.UserName FROM Tickets
INNER JOIN Users Informers ON Tickets.EnteredBy = Users.UserID
INNER JOIN Users Fixers ON Tickets.FixedBy = Users.UserID
INNER JOIN Users Supervisors ON Ticket.ResponsibleUser = Users.UserID
WHERE...
Sorry as i am not able to understand your words, but if I assumed your need correctly.. just for a try this could help you..
if you need either of them i.e. all users who has either entered or fixed or saw an issue you can find by..
Select t.Ticketnumber, t.EnteredBy, t.Issue, u.UserID ,u.UserName FROM Tickets t
INNER JOIN Users u ON t.EnteredBy = u.UserID or t.FixedBy = u.UserID
or t.ResponsibleUser = u.UserID;
And If you need all users who has entered, fixed and saw an issue you can find by..
Select t.Ticketnumber, t.EnteredBy, t.Issue, u.UserID ,u.UserName FROM Tickets t
INNER JOIN Users u ON t.EnteredBy = u.UserID and t.FixedBy = u.UserID
and t.ResponsibleUser = u.UserID;

Using left join for the same table or is there a better way?

I have a table called bans where I have the follow fields:
room_id, banned_user_id, banned_by_id, reason, ts_start, ts_end
The users data come from the table called users, now I wanted to query the bans to retrive the name of who was banned and by who along with reason, time the ban was placed and time it ends.
So I have this query:
SELECT u.username, us.username, b.reason, b.ts_start, b.ts_end
FROM `bans` b
LEFT JOIN users us ON b.banned_by_uid = us.uid
LEFT JOIN users u ON b.banned_uid = u.uid
WHERE room_id = 3
My question here is wether my query is ok by using the LEFT JOIN for the 2 data I have to grab from the table users or there is a different approach for this kinda of scenario ?
Your query is perfectly acceptable. Each join to users is on a specific ID, which translates into a simple lookup, with minimal overhead.