snippetsqlMinor
How to combine UNION and INNER JOIN?
Viewed 0 times
combineunionjoinhowandinner
Problem
I'm fetching the grandparent of all nodes in a tree as follows:
There is no entry with
I was planning to
SELECT P.id, P.parent, GP.parent gp_id FROM product_groups P
INNER JOIN product_groups GP ON P.parent = GP.idThere is no entry with
id=0 in the table, but some where parent=0, indicating roots of the trees. Those rows are not fetched by this query, as there's no grandparent to join them with. I'd like those rows returned, with 0 (or NULL) for both parent and gp_id.I was planning to
UNION the second table with (0,0), but can't figure out the syntax. How to do this?Solution
Just do a
That will return all rows from
LEFT JOIN instead:SELECT P.id, P.parent, GP.parent gp_id FROM product_groups P
LEFT JOIN product_groups GP ON P.parent = GP.idThat will return all rows from
P and any non-matching rows in GP will have NULL values.Code Snippets
SELECT P.id, P.parent, GP.parent gp_id FROM product_groups P
LEFT JOIN product_groups GP ON P.parent = GP.idContext
StackExchange Database Administrators Q#15399, answer score: 8
Revisions (0)
No revisions yet.