具有嵌套连接和选择的SQL查询

时间:2012-10-19 23:09:45

标签: mysql sql syntax

我正在尝试从我的数据库中的菜单项列表中的多层菜单中组合在一起。这是我的查询。 fl =第一级,sl =第二级等等。

以下是查询:

SELECT name as flName,id AS flId
FROM menu_items AS m1
WHERE parent_id = 0
INNER JOIN (SELECT name AS slName, id AS slId, parent_id AS slPid FROM menu_items)
m2 ON m1.firstLevelId = m2.parent_id
INNER JOIN (SELECT name AS tlName, id AS tlId, parent_id AS tlPid FROM menu_items)
m3 ON m2.id = m3.parent_id

我得到的错误是:

PersistenceException: Query threw SQLException:You have an error in your SQL syntax.  
check the manual that corresponds to your MySQL server version for the right syntax to 
use near 'INNER JOIN (SELECT name AS slName, id AS slId, parent_id AS slPid FROM  
menu_item'

但它看起来对我有用,我不知道..很确定我以前在子查询上做过连接。我做错了吗?

1 个答案:

答案 0 :(得分:3)

将where子句移到最后,如下所示:

SELECT name as flName,id AS flId
FROM menu_items AS m1 INNER JOIN (
        SELECT name AS slName, id AS slId, parent_id AS slPid FROM menu_items
    ) m2 ON m1.firstLevelId = m2.parent_id
    INNER JOIN (
        SELECT name AS tlName, id AS tlId, parent_id AS tlPid FROM menu_items
    ) m3 ON m2.id = m3.parent_id
WHERE parent_id = 0