根据关系表从不同的表中获取结果

时间:2017-06-30 10:13:37

标签: sql-server relationship

继续上一篇文章:

Get results from multiple tables based on relationship table

请参阅我试图完成的内容:

http://sqlfiddle.com/#!6/657f3/3

我还有两个与User表有关系的附加表(组织和组)。唯一的区别是关系是在关系表中以另一种方式定义的。

我想要的是每个用户的一行,其他列是从其他表中获取的。

我现在得到的是什么:

Id  Name    PhoneNumber Organization    GroupName
1   John    1234    Organization1   (null)
1   John    1234    (null)  Group1
2   Mary    5555    Organization2   (null)
3   Michael (null)  Organization2   (null)
3   Michael (null)  (null)  Group2

我想要的是什么:

Id  Name    PhoneNumber Organization    GroupName
1   John    1234    Organization1   Group1
2   Mary    5555    Organization2   (null)
3   Michael (null)  Organization2   Group2

你能帮我理解这里发生了什么,我怎么能解决这个问题?

1 个答案:

答案 0 :(得分:1)

我看到了你的例子,也许你需要一个group by

SELECT u.Id
    ,u.Name
    ,max(p.PhoneNumber) AS PhoneNumber
    ,Max(c.Name) as Organization
    ,Max(g.Name) as GroupName
FROM Users u
LEFT JOIN Relationship r ON r.Id = u.Id
LEFT JOIN Phone p ON p.Id = r.ChildId
LEFT JOIN Relationship rr ON rr.ChildId = u.Id
LEFT JOIN Organizations c ON c.Id = rr.Id
LEFT JOIN Groups g ON g.Id = rr.Id
GROUP BY u.Id
         ,u.Name