簡體   English   中英

Sql查詢distinct +其他列

[英]Sql query distinct + other columns

例如,我有這樣的sql消息表:

Id   from_user_id   to_user_id    message
1    1              2             Hello
2    1              2             How are you?
3    1              3             Where are you?

並查詢SELECT DISTINCT to_user_id FROM消息; 它返回

to_user_id
2
3

但是,這還不夠。 我需要向其他用戶顯示from_user_id(id = 1)的所有最后消息,並避免N + 1查詢問題。 結果必須是這樣的

Id   from_user_id   to_user_id    message
2    1              2             How are you?
3    1              3             Where are you?

你想要自我加入:

SELECT    m.*
FROM      messages m
LEFT JOIN messages _m ON m.to_user_id = _m.to_user_id
AND       _m.id > m.id
WHERE     _m.id IS NULL

您可以使用分析函數排名,並在組中對其進行排序...

select * from (
select id,
       from_user_id,
       to_user_id,
       message,
       rank () over (partition by from_user_id, to_user_id order by id desc) rnk
from   table_name
) t1 where rnk = 1

這假設id列是順序生成的數字,因此在id為2的消息之后創建了id為3的消息。通常,如果你有一個timestamp列,那么它將更符合邏輯。 在這種情況下,您可以order by timestamp desc使用order by timestamp desc

Postgres提供了distinct on ,這通常是解決此類問題的最佳方式:

select distinct on (to_user_id) m.*
from messages m
where m.from_user_id = 1
order by to_user_id, id desc;

暫無
暫無

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

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