我该怎么办:
rooms_message
discussions_messages
)discussions_replies
)?我有3张桌子:
rooms_messages
id | 房间_uuid | 讨论_消息_uuid | 创建于 |
---|---|---|---|
1 | 10 | 101 | 2024-07-16 12:30:45 |
2 | 20 | 102 | 2024-07-16 12:30:50 |
3 | 10 | 103 | 2024-07-16 12:32:45 |
4 | 20 | 104 | 2024-07-16 12:34:50 |
5 | 20 | 105 | 2024-07-16 12:36:50 |
discussions_messages
id | 文字 |
---|---|
101 | 你好 |
102 | 测试 |
103 | 好的 |
104 | 哇 |
105 | 你好2 |
discussions_replies
id | 讨论_消息_uuid | 文字 |
---|---|---|
201 | 101 | 你好 |
202 | 101 | 测试 |
203 | 102 | 好的 |
204 | 102 | 哇 |
我使用来自https://stackoverflow.com/a/38505618的请求,它可以按created_at顺序列出room_messages。但我没有正确的 rooms_messages.uuid:
select URL, max(DateVisited)
from <table>
group by URL
我的询问:
SELECT rm.uuid as uuid, max(rm.created_at) as created_at, rm.room_uuid as room_uuid, rm.discussion_message_uuid as discussion_message_uuid, dm.text,
FROM rooms_messages AS rm
INNER JOIN discussions_messages AS dm ON rm.discussion_message_uuid = dm.uuid
LEFT JOIN discussions_replies AS dr ON dm.uuid = dr.discussion_message_uuid
GROUP BY room_uuid
但是我有3个问题:
您当前的查询无效,甚至无法在启用
ONLY_FULL_GROUP_BY
标志的 MySQL 上运行(它应该是这样)。 我们可以在这里使用 ROW_NUMBER()
来获得正确的解决方案:
WITH cte AS (
SELECT rm.uuid as uuid, rm.created_at, rm.room_uuid,
rm.discussion_message_uuid, dm.text,
ROW_NUMBER() OVER (PARTITION BY rm.room_uuid ORDER BY rm.created_at DESC) rn
FROM rooms_messages AS rm
INNER JOIN discussions_messages AS dm ON rm.discussion_message_uuid = dm.uuid
LEFT JOIN discussions_replies AS dr ON dm.uuid = dr.discussion_message_uuid
)
SELECT uuid, created_at, room_uuid, discussion_message_uuid, text
FROM cte
WHERE rn = 1;