I have a table called 'menus':
menu_id | sort | page_id | parent_page_id
---------|------|---------|----------------
1 | 0 | 1 | NULL
1 | 1 | 2 | 1
1 | 2 | 3 | 1
1 | 3 | 4 | 1
And a table called 'pages':
id | url
----|-----------
1 | vehicles
2 | car
3 | bicycle
4 | bus
I chose to store the data into separate tables because one page can be included in multiple menus.
Now I want to do a query from which the result is:
menu_id | page_id | sort | url | parent_url
---------|---------|------|----------|------------
1 | 1 | 0 | vehicles | NULL
1 | 2 | 1 | car | vehicles
1 | 3 | 2 | bicycle | vehicles
1 | 4 | 3 | bus | vehicles
The columns menu_id
, page_id
, sort
and url
can easily be retrieved using a LEFT JOIN:
SELECT
menus.menu_id,
pages.id AS page_id,
menus.sort,
pages.url
FROM menus
LEFT JOIN pages
ON menus.page_id = pages.id
ORDER BY sort
But how do I get the column parent_url
in the query result?
Best Answer
You will want to JOIN to the
pages
table a second time to get theparentURL
. The first time that you join topages
use thepage_id
, then the second join will use theparent_page_id
:See SQL Fiddle with Demo. This gives a result: