gpt4 book ai didi

Mysql左连接合并列

转载 作者:行者123 更新时间:2023-11-29 01:30:40 26 4
gpt4 key购买 nike

+----------------------+
| 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 |
+----------+---------+-------------------------+

我得到了这两个表名 postpost_repliespost_replies 中的 post_id 是表 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 返回消息

有可能吗?

非常感谢任何帮助

最佳答案

联合您提供的两个查询并引入正确的顺序:

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”。

关于Mysql左连接合并列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14182221/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com