如何从消息表中获取对话列表?

Posted

技术标签:

【中文标题】如何从消息表中获取对话列表?【英文标题】:How to get a list of conversations from the message table? 【发布时间】:2021-07-19 01:00:16 【问题描述】:

行如下:

|id.   |sender|receiver| type| content   | time |
|------|------|--------|-----|-----------|------|
|uuid01|     x|       y| text|      hello|time01|
|uuid02|     y|       z| text|how are you|time02|
|uuid03|     y|       x| text|       haha|time03|
|uuid04|     x|       y|image|           |time04|

如何将 x->y / y->x 合并为一个对话?如下:

|id |type | content   | time |
|---|-----|-----------|------|
|x-y|image|           |time04|
|y-z|text |how are you|time02|

【问题讨论】:

【参考方案1】:

假设所有涉及的列NOT NULL

SELECT DISINCT ON (LEAST(sender, receiver), GREATEST(sender, receiver))
       LEAST(sender, receiver) || '-' || GREATEST(sender, receiver) AS id
     , type, content, time
FROM   tbl
ORDER  BY LEAST(sender, receiver), GREATEST(sender, receiver), time DESC;

见:

Select first row in each GROUP BY group? SQL Sorting table based on two interchangeable fields How to create a Postgres table with unique combined primary key?

性能优化是可能的,具体取决于您的关系设计和数据分布的未公开细节。

【讨论】:

【参考方案2】:

这样您可以通过交换多于两列的值进行分组:

定义函数array_sort:

CREATE OR REPLACE FUNCTION array_sort(ANYARRAY)
RETURNS ANYARRAY LANGUAGE SQL
AS $$
SELECT ARRAY(SELECT unnest($1) ORDER BY 1);
$$;

Sql查询:

SELECT DISTINCT ON (array_sort(string_to_array(sender, ',') || string_to_array(receiver, ',')))
   sender || '-' || receiver AS idSR,
   type,
   content,
   time
FROM messages
ORDER BY array_sort(string_to_array(sender, ',') || string_to_array(receiver, ',')), id DESC;

【讨论】:

以上是关于如何从消息表中获取对话列表?的主要内容,如果未能解决你的问题,请参考以下文章

获取从 Outlook 表中获取的消息的 Outlook 邮件项

如何从 MySQL 表中选择消息列表?

Laravel 4.2:如何使用 whereIn() 和 with() 获取一对多关系中的项目列表?

react native - 如何从 sqlite 表中获取“狗”列表?

如何从价格变化的 SQL 表中获取列表

如何从Oracle数据库中的表中获取列名(字段名)列表?