如何获得按不同列排序的不同结果? SQL PostgreSQL

How to get a distinct result ordered by a different column? SQL Postgresql

我正在尝试找出在 postgresql 中执行此查询的最佳方法。我有一条消息 table,我想获取用户从每个不同用户收到的最后一条消息。我需要 select 行中的所有内容。

我想这是我想按发件人 ID "msgfromid" 分组的地方,但是当我这样做时它抱怨我没有将我的 select 语句中的所有内容都包含在我的组中by 语句,但我只想按一列分组,而不是全部。因此,如果我尝试在一列上使用 Distinct,它会强制我首先按 'distinct on' 列排序 ("msgfromid"),这会阻止我获得所需的正确行(按最后一个排序)发件人发送的消息 "msgsenttime").

我的目标是使它在我的服务器和数据库上尽可能高效。

这就是我现在拥有的,无法正常工作。 (这是我之后用来加入相关信息的另一个查询的子查询,但我认为这是不相关的)

SELECT DISTINCT ON ("msgfromid") "msgfromid", "msgid", "msgtoid", "msgsenttime", "msgreadtime", "msgcontent", "msgreportstatus", "senderun", "recipientun" 
FROM "messages"  
WHERE "msgtoid" = ?
ORDER BY "msgsenttime" desc, "msgfromid"

我想如果我在子查询中预先订购它们可能会起作用,但它似乎只是随机选择一个,这不是很有效,即使它能起作用,因为我把每条消息都拉出来,对吧?:

SELECT DISTINCT ON ("msgfromid") "msgfromid", "msgid", "msgtoid", "msgsenttime", "msgreadtime", "msgcontent", "msgreportstatus", "senderun", "recipientun"      
FROM        
( 
    SELECT * FROM "messages"
    WHERE "msgtoid" = ?
    ORDER BY "msgsenttime" desc  
) as "mqo"

感谢您的帮助。

您的 order by 键顺序错误:

SELECT DISTINCT ON ("msgfromid") m.*
FROM "messages" m 
WHERE "msgtoid" = ?
ORDER BY "msgfromid", "msgsenttime" desc;

对于DISTINCT ON,括号中的键需要是ORDER BY中的第一个键。

如果您希望最终结果以不同的方式排序,那么您需要使用子查询,在外部查询上使用不同的 ORDER BY