I currently have one MySQL table of posts for a forum. This includes parent posts and child posts. If it is a parent post, it has a topic
. If it is a child post, it includes a parent_id
.
E.g.:
TABLE posts
+----+-----------+---------+--------+------+
| id | parent_id | topic | author | body |
+----+-----------+---------+--------+------+
| 1 | NULL | "Hello" | "Me" | ... |
| 2 | 1 | NULL | "Me" | ... |
+----+-----------+---------+--------+------+
I would like to run one SQL query, similar to the following:
SELECT id, 'self' AS parent_id, topic, author, body FROM posts WHERE parent_id IS NULL,
UNION
SELECT id, parent_id, (SELECT topic WHERE id=parent_id) as topic FROM posts WHERE topic IS NULL
Desired output:
+----+-----------+---------+--------+------+
| id | parent_id | topic | author | body |
+----+-----------+---------+--------+------+
| 1 | "self" | "Hello" | "Me" | ... |
| 2 | 1 | "Hello" | "Me" | ... |
+----+-----------+---------+--------+------+
Basically, I want to return the parent topic without having to run multiple queries. Is there any way to do this? Should I just add a "parent_topic" field instead?
Thanks!