【问题标题】: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|

【问题讨论】:

    标签: sql postgresql greatest-n-per-group


    【解决方案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;
    

    见:

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

    【讨论】:

      【解决方案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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-22
        相关资源
        最近更新 更多