Get results from multiple tables based on relationship table

大兔子大兔子 提交于 2019-12-10 22:28:26

问题


I have dbo.Users tables

Id, Name
1, John
2, Mary
3, Michael

Then I have dbo.Phones table

Id, Phonenumber
10, 1234
11, 5555

Then I have dbo.Relationship table

Id, ChildId
1, 10
2, 11

How could I make a query that returns

Id, Name, Phonenumber
1, John, 1234
2, Mary, 5555
3, Michael, NULL

This is what I got so far.

SELECT u.Id, u.Name, p.Phonenumber
FROM dbo.Users as u
LEFT JOIN dbo.Phones as p
-- Something

SQL Fiddle


回答1:


Think of the Relationship table as the middle-man between your Users and Phones tables here. It is a many-to-many relationship with a mapping table. Join your Users to the Relationship and then the Relationship to your Phones.

SELECT u.Id
    ,u.Name
    ,p.PhoneNumber
FROM dbo.Users u
LEFT JOIN dbo.Relationship r ON r.Id = u.Id
LEFT JOIN dbo.Phones p ON p.Id = r.ChildId

Think of it like:

Users: Hello Relationship, I have UserId = 1, what PhoneIds do I have for that UserId?

Relationship: Hi Users. I have PhoneId = 10 for you. I'll go talk to Phones to see what the number is.

Phones: Hi Relationships! I have PhoneNumber 1234 for you. It matches the PhoneId you gave me.




回答2:


Join them on id field.I would use inner join depending on the requirement

SELECT distinct u.Id, u.Name, p.Phonenumber
FROM dbo.Users as u
LEFT JOIN dbo.Phones as p on u.id = p.id

or---

 SELECT distinct u.Id, u.Name, p.Phonenumber
    FROM dbo.Users as u
    inner join T JOIN dbo.Phones as p on u.id = p.id
    inner join dbo.relationship r on r.id = u.id
where----



回答3:


try this :

Select u.Id, u.Name, p.Phonenumber
From
Users u 
Left join Relationship r on r.Id = u.Id
Left join Phones p on r.ChildId = p.Phonenumber


来源:https://stackoverflow.com/questions/44825791/get-results-from-multiple-tables-based-on-relationship-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!