簡體   English   中英

Postgres SQL 查詢以獲取不同 id 的第一行

[英]Postgres SQL query to get the first row of distinct id

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
 

您可以使用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;

distinct on使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM