【问题标题】:How to select all from one table order by the last created timestamp of values from another table如何通过另一个表中值的最后创建时间戳从一个表顺序中选择所有值
【发布时间】:2021-07-03 13:28:10
【问题描述】:

我有 2 个表,分别名为 conversationmessage

我想选择按与对话相关的最后更新消息的顺序排序的所有对话。对话表没有updated_at,并且能够得到最后一个updated_at排序的所有对话,应该从表message的对话中最后创建的消息中扣除。

结果应该基于对话的最后一条消息。

我尝试的 SQL 没有给我正确的结果,我相信我应该使用连接,但由于我是 SQL 新手,所以无法真正了解它是如何实现的

select
    *
from
    conversation
inner join message on
    conversation.id = message.conversation_id
order by
    message.updated_at desc;    

表格如下

对话

id topic origin_type origin_id created_at
1 t1 doc1 xx1 2021-04-07 13:23:40
2 t2 doc2 xx2 2021-04-07 14:23:40
3 t3 doc3 xx3 2021-04-07 15:23:40

消息表

id conversation_id message created_at updated_at
1 1 xxx 2021-04-07 13:23:40 2021-04-07 13:23:40
2 2 xxx 2021-04-07 14:23:40 2021-04-07 14:23:40
3 3 xxx 2021-04-07 15:23:40 2021-04-07 15:23:40

看到表格我应该得到如下选择的结果,我相信 conversation.id = 3 包含最后创建和最近的消息。

id conversation_id
1 3
2 2
3 1

在 SQL/PSQL 中我不知道如何进行这种选择

【问题讨论】:

  • 如果您希望您的消息传递应用程序将被大量用户使用,最好将此数据保存在conversation 表中,以免读取所有转换以在以后对它们进行排序或所有消息以查找每个对话的最新消息(此外,每个对话包括多个人但相同的最新消息)。
  • 我很欣赏这个建议,但我有一些细节要求我保持这种特定的方式

标签: sql postgresql


【解决方案1】:

您的数据不是特别说明性的,因为对话只有一条消息。但是,我认为您希望将所有行保持在一起进行对话。这将使用窗口函数来获取每个对话的最大更新时间:

order by max(message.updated_at) over (partition by conversation.id) desc,
         conversation.id,
         message.updated_at desc

编辑:

如果您只想要没有消息信息的对话,您可以使用子查询:

select c.*
from conversations c
order by (select max(m.updated_at) from messages m where m.conversation_id = c.id) desc;

【讨论】:

  • 为了简单起见,我放了一条消息,但是应该更多,因为每个对话都可以有很多消息,但主题不会改变。我会试试你的建议。
  • 我试过了,但结果不对,我得到的结果是 1111、2222、33333333、444444444 等等,我应该只返回对话顺序,结果中没有消息和重复项。就像我之前分享的一样,比如 1 2 3 4 等等,按最后创建或更新的对话消息排序
【解决方案2】:

您可以只使用标量子查询:

select *,
    (
        select max(m.updated_at) from message m
        where m.conversation_id = c.conversation_id
    ) as last_updated_at
from conversation c
order by last_updated_at desc;  

【讨论】:

    猜你喜欢
    • 2014-12-16
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 2017-02-23
    相关资源
    最近更新 更多