douci6541 2015-07-20 18:35
浏览 92
已采纳

如何在单个SQL查询中处理多对多关系?

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.

enter image description here

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';
  • 写回答

1条回答 默认 最新

  • douyingmou1389 2015-07-20 18:40
    关注

    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';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料