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
.
Eg:
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!
The following SQL will do what you're looking for:
select p_child.id, if(p_child.parent_id is null, 'self', p_child.parent_id) as parent_id, if(p_parent.id is null, p_child.topic, p_parent.topic) as topic, p_child.author, p_child.body
from posts p_child
left join posts p_parent on p_child.parent_id = p_parent.id;
Try this query, if the parent_id is not null
, I am selecting the parents' topic
in a sub-query. I am using case
to do that.
SELECT id,
CASE WHEN parent_id IS NULL THEN 'SELF'
ELSE parent_id
END as parent_id
CASE WHEN parent_id IS NOT NULL THEN (SELECT t.topic FROM posts as t WHERE t.id = m.parenyt_id)
ELSE topic
END as Topic,
author,
body
FROM posts as m
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.