我目前有一個MySQL論壇表的帖子。這包括家長帖子和子帖子。如果它是一個父職位,它有一個topic
。如果是兒童帖子,則包含parent_id
。MySQL - SELECT ...(子查詢)AS字段名稱
如:
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」字段嗎?
謝謝!
WHEN PARENT_ID爲null,則 '自我' ELSE PARENT_ID END'可以使用的情況下,'CASE。 – user2989408
我的問題在於從父帖子返回「主題」字段:) – Trey