我目前有一个MySQL论坛帖子。这包括父帖和子帖。如果是父帖子,则其为topic
。如果是儿童帖子,则其中包含parent_id
。
E.g:
TABLE posts
+----+-----------+---------+--------+------+
| id | parent_id | topic | author | body |
+----+-----------+---------+--------+------+
| 1 | NULL | "Hello" | "Me" | ... |
| 2 | 1 | NULL | "Me" | ... |
+----+-----------+---------+--------+------+
我想运行一个SQL查询,类似于以下内容:
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
期望的输出:
+----+-----------+---------+--------+------+
| id | parent_id | topic | author | body |
+----+-----------+---------+--------+------+
| 1 | "self" | "Hello" | "Me" | ... |
| 2 | 1 | "Hello" | "Me" | ... |
+----+-----------+---------+--------+------+
基本上,我想返回父主题,而不必运行多个查询。有没有办法做到这一点?我应该只添加一个“parent_topic”字段吗?
谢谢!
答案 0 :(得分:1)
以下SQL将执行您正在寻找的内容:
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;
答案 1 :(得分:0)
尝试此查询,如果parent_id is not null
,我在子查询中选择父项topic
。我正在使用case
来做到这一点。
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