Lets say I've got the following table which is a familiar example.
+----------------------------------+
| TAGS |
+--------+-------------+-----------+
| tag_id | tag_name | parent_id |
+--------+-------------+-----------+
| 1 | programming | NULL |
| 2 | php | 1 |
| 3 | class | 2 |
| 4 | object | 2 |
| 5 | method | 3 |
+--------+-------------+-----------+
I'm trying to devise a query which selects the associated parent_id
and tag_name
based on the value of the initial select statement.
Something like this:
SELECT * FROM tags AS child
WHERE child.tag_name = 'object'
UNION
SELECT * FROM tags AS parent
WHERE parent.parent_id = child.parent_id
I need to be able to return the combined rows from both these queries which is why I'm using UNION
.
The expected result should be:
+--------+-------------+-----------+
| tag_id | tag_name | parent_id |
+--------+-------------+-----------+
| 2 | php | 1 |
| 4 | object | 2 |
+--------+-------------+-----------+
I also think that a JOIN
may work but I can't quite make it work.