【问题标题】:Postgres SQL query to get the first row of distinct idPostgresql查询以获取不同ID的第一行
【发布时间】:2021-02-16 10:31:49
【问题描述】:

channels

id |  name 
------------
1  | ABC
2  | XYZ
3  | MNO
4  | ASD

user_channels

user_id |  channel_id 
----------------------
 555    | 1
 666    | 1
 777    | 1
 555    | 2
 888    | 2
 999    | 3
 555    | 3 

user_chats

 id | created_at | channel_id | content
---------------------------------------
 2  | time 1     | 1          | Hello
 3  | time 2     | 1          | Hi
 4  | time 3     | 2          | Good day
 5  | time 4     | 2          | Morning

我在 postgres SQL 中有这 3 个表,

我想编写一个 sql 查询以通过 user_id 获取 user_channels,它只是来自 user_chats 表的最新消息 (time 1 is oldest message)。我该怎么做?

例如,对于 user_id = 555,查询应该返回

 channel_id | content  | created_at
---------------------------------------
 1          | Hi       | time 2
 2          | Morning  | time 4  
 3          | Null     | Null
 

【问题讨论】:

    标签: sql postgresql sql-order-by inner-join greatest-n-per-group


    【解决方案1】:

    你可以使用distinct on:

    select distinct on (c.channel_id) c.channel_id, uc.content, uc.created_at
    from user_channels c left join
         user_chats uc
         on uc.channel_id = c.channel_id
    where c.user_id = ?
    order by c.idchannel_id, uc.created_at desc;
    

    【讨论】:

    • 如何在这个查询中把空行放在最后?
    • 这个查询没有得到我想要的。我想按 created_at desc 而不是 channel_id 排序
    • @KumarKumar 。 . .我不明白。你的意思是你希望结果集以不同的方式排序?这应该返回正确的行集。
    【解决方案2】:

    使用distinct on:

    select distinct on (a.channel_id) a.*
    from user_chats a
    inner join user_channels l on l.channel_id = a.channel_id
    where l.user_id = 555
    order by a.channel_id, a.createt_at desc
    

    如果您希望同时为所有用户使用此功能:

    select distinct on (l.user_id, a.channel_id) l.user_id, a.*
    from user_chats a
    inner join user_channels l on l.channel_id = a.channel_id
    order by l.user_id, a.channel_id, a.createt_at desc
    

    【讨论】:

      猜你喜欢
      • 2019-04-26
      • 2021-05-29
      • 1970-01-01
      • 2020-06-17
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      • 2019-02-18
      相关资源
      最近更新 更多