选择不同的列和最新的created_ad并附加有很多

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

我想知道我该怎么做:

  • 列出房间最新的rooms_message
  • 带有discussions_messages.text(来自
  • discussions_messages
  • 和discussions_replies.replies(属于discussions_messages)(来自
  • discussions_replies
目前我有3张桌子:

房间消息:

id房间_uuid讨论_消息_uuid创建于1101012024-07-16 12:30:452201022024-07-16 12:30:503101032024-07-16 12:32:454201042024-07-16 12:34:505201052024-07-16 12:36:50
讨论_消息:

id文字101你好102测试103好的104哇105你好2
讨论_回复:

id讨论_消息_uuid文字201101你好202101测试203102好的204102哇
我使用来自

https://stackoverflow.com/a/38505618的请求,并且可以按create_at order by显示列表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 database database-design
1个回答
0
投票
您当前的查询无效,甚至无法在启用

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.