简体   繁体   中英

How to handle many-to-many relationships in a single sql query?

I've been running SQL calls all morning, without any luck on getting the correct kind of data that I want to return. I did a few searches and found some information on Joining 2 tables, but nothing that pulls from a table, that pulls from a table. This can sound confusing by wording so I crafted a diagram of the sort of information I'm looking to get.

在此处输入图片说明

I have tried things like,

select * from Users 
left join UserLibs on UserLibs.userId = Users.UserId
WHERE Users.username='testname'

That however doesn't give me the library name.

So then I tired to join the column with another table and column.

select * from users
left join UserLibs on userLibs.userId = Users.UserId AND left join Libraries on  UserLibs.libraryId = Libraries.libraryName
where Users.username='test';

Which also didn't produce results, just errors. Any help with this would be awesome.

UPDATE

I just wanted to add my final solution that worked for my situation.

SELECT Users.userId, Users.username, Users.editLibraries, Users.editAnnouncements, Users.editServices, 
   Users.editNormalHours, Users.editSpecialHours, Users.editUsers, Users.editSemesters, 
   Libraries.libraryName, LibraryDepartment.departmentName
    FROM Users
    LEFT JOIN UserLibs on Users.userId = UserLibs.userId
    LEFT JOIN Libraries on UserLibs.libraryId = Libraries.id
    LEFT JOIN UserDepts on Users.userId = UserDepts.userId
    LEFT JOIN LibraryDepartment on UserDepts.departmentId = LibraryDepartment.ldId
    WHERE Users.username='testname';

You don't use AND to perform multiple joins. You just just keep joining tables. You can join as many you like. For example:

select *
from users
left join userlibs
on users.userid=userlibs.userid
left join libraries
on userlibs.libraryid=libraries.libraryid
where username='test';

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