在created_at上选择不同的列和最新的列,并附加有许多[重复]

问题描述 投票:0回答:1

我该怎么办:

  • 列出房间最新的
    rooms_message
  • 与discussion_messages.text(来自
    discussions_messages
  • 和discussion_replies.replies(属于discussion_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个问题:

  • rm.uuid 不正确:它不是最新的
  • 结果:dm.text 不是最新的,因为 rm.uuid 不是最后一个
  • 结果:我不加载回复
sql mysql greatest-n-per-group
1个回答
1
投票

您当前的查询无效,甚至无法在启用

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;
© www.soinside.com 2019 - 2024. All rights reserved.