I have a comments
table with the following content
id | parent_id | content |
---|---|---|
1 | NULL | A |
2 | NULL | B |
3 | NULL | C |
4 | 1 | AA |
5 | 1 | AB |
6 | 1 | AC |
7 | 5 | ABA |
8 | 5 | ABB |
And I want to select comment with id = 1, all of it children and grand children. Something like this
id | parent_id | content |
---|---|---|
1 | NULL | A |
4 | 1 | AA |
5 | 1 | AB |
6 | 1 | AC |
7 | 5 | ABA |
8 | 5 | ABB |
For now I use the following query:
SELECT * FROM comments WHERE id = 1
UNION
SELECT * FROM comments WHERE parent_id IN (SELECT id FROM comments WHERE id = 1)
UNION
SELECT * FROM comments WHERE parent_id IN (SELECT id FROM comments WHERE parent_id IN (SELECT id FROM comments WHERE id = 1));
But this solution can quickly become a huge mess and error prone. Especially when I also want to get the deeper children like grand grand grand children
So my question is there any way to make this query simpler? And maybe more performant?