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

How to get a list of conversations from the message table?

行如下:

|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|

这样您就可以通过交换超过两列的值来分组:

定义函数array_sort:

CREATE OR REPLACE FUNCTION array_sort(ANYARRAY)
RETURNS ANYARRAY LANGUAGE SQL
AS $$
SELECT ARRAY(SELECT unnest() 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;

假设所有涉及的列 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?

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