不止一个加入MYSQL?

时间:2013-01-21 15:27:55

标签: mysql sql join

**Sub Menu**
id|title
1 | Sub A

**Root_Sub**
id|root_id|sub_id
1 |9      |1


**Root Menu**
id|title
9 | Root X

我需要找出子菜单的根菜单的ID。

为此,我使用:

SELECT * FROM sub_menu LEFT JOIN root_sub ON sub_menu.id = root_sub.sub_id

这给了我'9'作为身份证。

但我还需要获取根菜单的标题,即获得标题'Root X'。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

SELECT  a.ID AS subID,
        a.title AS SubTitle,
        c.ID AS RootID,
        c.Title as RootTitle
FROM    sub_Menu a
        INNER JOIN root_sub b
            On a.ID = b.sub_ID
        INNER JOIn root_Menu c
            ON b.root_ID = c.ID

如果所有记录在其他表上至少有一个匹配,则首选INNER JOIN但如果可以为,则将INNER JOIN更改为LEFT JOIN < / p>

答案 1 :(得分:0)

SELECT *
FROM sub_menu
LEFT JOIN root_sub ON sub_menu.id = root_sub.sub_id
LEFT JOIN root_menu ON root_sub.root_id = root_menu.id