如何获得与父表ID相关的所有孙子

时间:2020-03-13 22:14:18

标签: mysql sql

我有3个相关的表,我想获取所有在其中定义了父ID的grandChild。我正在使用mySql和php。

        --------- RELATIOSHIP -------
        Parent has many child
        Child has many grandchild


        -------Parent table------
        | parentId | otherAttr  |
        -------------------------

        ------------ Child table ---------------
        |  childId  |  parentId  |  otherAttr  |
        ----------------------------------------

        ------------ grandChild table ----------
        |  grandId  |  childId  |  otherAttr  |
        ----------------------------------------

1 个答案:

答案 0 :(得分:0)

几个联接应该可以解决问题:

SELECT g.*
FROM   grandchild g
JOIN   child c ON g.childId = c.childId
JOIN   parent p ON c.parentId = p.parentId
WHERE  p.parentId = <somevalue>