+----------------------+
| post_id | message |
+----------------------+
| 1 | message 1 |
+----------------------+
| 2 | message 2 |
+----------------------+
+----------+---------+-------------------------+
| reply_id | post_id |message |
+----------+---------+-------------------------+
| 1 | 1 | reply 1 to message 1 |
+----------+---------+-------------------------+
| 2 | 1 | reply 2 to message 1 |
+----------+---------+-------------------------+
| 3 | 1 | reply 3 to message 1 |
+----------+---------+-------------------------+
| 4 | 2 | reply 1 to message 2 |
+----------+---------+-------------------------+
我有两个表名post
和post_replies
表post_id
中的post_replies
在表post
中为Fk到Pk
我想要做的是找到帖子消息,它只回复一列
如果我这样运行:
SELECT p.message, pr.message FROM `posts` AS p LEFT JOIN post_replies AS pr ON p.post_id = pr.post_id
它将返回类似这样的内容
+-----------+-------------------------+
| message | message |
+-----------+-------------------------+
| message 1 | reply 1 to message 1 |
+-----------+-------------------------+
| message 1 | reply 2 to message 1 |
+-----------+-------------------------+
| message 1 | reply 3 to message 1 |
+-----------+-------------------------+
| message 2 | reply 1 to message 2 |
+-----------+-------------------------+
有没有办法可以像这样获得结果:
+-------------------------+
| message |
+-------------------------+
| message 1 |
+-------------------------+
| reply 1 to message 1 |
+-------------------------+
| reply 2 to message 1 |
+-------------------------+
| reply 3 to message 1 |
+-------------------------+
| message 2 |
+-------------------------+
| reply 1 to message 2 |
+-------------------------+
如果我跑
SELECT p.message FROM `posts` AS p LEFT JOIN post_replies AS pr ON p.id = pr.post_id
这将从post
表
或
SELECT pr.message FROM `posts` AS p LEFT JOIN post_replies AS pr ON p.id = pr.post_id
这将仅从表post_replies
返回消息
无论如何都可能吗?
任何帮助非常感谢
答案 0 :(得分:3)
UNION您提供的两个查询并介绍正确的顺序:
SELECT * FROM (
SELECT p.id, 0 x, p.message
FROM posts AS p
LEFT JOIN post_replies AS pr ON p.id = pr.post_id
UNION ALL
SELECT p.id, pr.id, pr.message
FROM posts AS p
LEFT JOIN post_replies AS pr ON p.id = pr.post_id
) x
ORDER BY 1, 2
如果您不想要重复,请将“UNION ALL”更改为“UNION”。
答案 1 :(得分:2)
我知道这不是你想要的,但只是发帖如果能解决你的问题
$查询
SELECT
group_concat(pr.message SEPARATOR '|'), p.message,
FROM
`posts` AS p
LEFT JOIN
post_replies AS pr ON p.post_id = pr.post_id
GROUP BY
pr.post_id
+-----------+----------------------------------------------------------------------------+
| message | message |
+-----------+----------------------------------------------------------------------------+
| message 1 | reply 1 to message 1 | reply 2 to message 1 | reply 3 to message 1 |
+-----------+----------------------------------------------------------------------------+