简体   繁体   中英

SQL Query with nested joins and selects

I'm trying to put together from a multi-tier menu from a list of menu items in my db. Here's my query to do it. fl=first level, sl= second level, etc.

Here's the query:

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

And the error I'm getting is this:

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'

But it looks valid to me, I dunno.. Pretty sure I've done joins on subqueries before. Am I doing something else wrong?

Move the where clause to the end, like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM