MYSQL通过多层关系查询一对多关系

时间:2013-09-27 16:30:40

标签: mysql

如何从多对多关系中选择所有内容,在多对多关系中选择多个层次?我不确定如何嵌套所有左连接。

实施例

There are many Institutions
Each Institution has many Departments
Each Department has many Forums
Each Forum has many Users
Each User has many Posts
Each Post has many Comments

查找机构的所有评论。

我用Google搜索,但我不确定这个名称是什么 - 链接嵌套一对多关系查询?我找到的最接近的是SQL left join vs multiple tables on FROM line?

1 个答案:

答案 0 :(得分:3)

不知道你的架构并做出一些假设:

SELECT c.*
FROM
    Institution i
    INNER JOIN Department d ON d.InstitutionID = i.InstitutionID
    INNER JOIN Forums f ON f.DepartmentID = d.DepartmentID
    INNER JOIN `User` u ON u.ForumID = f.ForumID
    INNER JOIN Post p ON p.UserID = u.UserID
    INNER JOIN Comment c ON c.PostID = p.PostID
WHERE
    i.InstitutionID = 42