I currently have the following SQL query wich retrieves a record from a table and also it's parents and grandparent. The only issue I have is that it's returned as a single record. I would like it return as multiple rows, as it's stored in the database.
Current structure:
comment_id | parent_comment_id
1 3
2 7
3 5
7 11
SQL:
SELECT p3.comment_id as `Grandparent`, p2.comment_id as `Parent`, p1.comment_id as `Child`
FROM comments p1
LEFT JOIN comments p2 on p1.comment_id = p2.parent_comment_id
LEFT JOIN comments p3 on p2.parent_comment_id = p3.comment_id
WHERE p1.comment_id = 1
Current Output (single row):
Grandparent | Parent | Child
5 3 1
Desired Output (separate rows):
comment_id
5
3
1
I am editing some existing mysql
code, I do not have the option to convert everything to mysqli
or pdo
at the moment.
try this:
select comment_id from cm where comment_id = 1
union
select parent_comment_id from cm where comment_id =1
union
select g.parent_comment_id from cm g
join cm p
on p.parent_comment_id = g.comment_id
where p.comment_id = 1;
please verify the logic and make sure it gives you the correct result.
Demo: SQLFiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.