Skip to content
Advertisement

SQL – return a value referenced by initial value from same table

I’m sure this has been asked before, but I can’t seem to find any questions that help.

Here’s an example of a table:

I’m trying to figure out how to write a single query which, given ID=1, will return me rows 1 and 3. Is this possible without making two queries?

Also, is there a way to return the information of the parent as a custom column? So, rather than returning 2 rows, returning the row where id=1 with parent_id=3 added on?

Advertisement

Answer

You can use union all and exists:

If you want to do this over multiple levels of hierarchy, then you would typically use a recursive query. The syntax slightly varies accross databases (and not all of them support recursion), but the idea is:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement