How to get a distinct result ordered by a different column? SQL Postgresql -
i'm trying figure best way perform query in postgresql. have messages table , want grab last message user received each distinct user. need select row.
i think want group senders id "msgfromid", when complains haven't included select statement in group statement, want group 1 column, not of them. if try use distinct on 1 column forces me order 'distinct on' column first ("msgfromid") prevents me being able correct row need (ordered last message sent sender "msgsenttime").
my goal make efficient possible on server , database.
this have right now, not working. (this sub-query of query use join relevant information afterwards figure irrelevant)
select distinct on ("msgfromid") "msgfromid", "msgid", "msgtoid", "msgsenttime", "msgreadtime", "msgcontent", "msgreportstatus", "senderun", "recipientun" "messages" "msgtoid" = ? order "msgsenttime" desc, "msgfromid"
i thought maybe if pre-ordered them in sub-query work seems randomly pick 1 anyway, , can't efficient, if work, since i'm pulling every message out begin with, right?:
select distinct on ("msgfromid") "msgfromid", "msgid", "msgtoid", "msgsenttime", "msgreadtime", "msgcontent", "msgreportstatus", "senderun", "recipientun" ( select * "messages" "msgtoid" = ? order "msgsenttime" desc ) "mqo"
thanks help.
your order by
keys in wrong order:
select distinct on ("msgfromid") m.* "messages" m "msgtoid" = ? order "msgfromid", "msgsenttime" desc;
for distinct on
, keys in parentheses need first keys in order by
.
if want final result ordered in different way, need use subquery, different order by
on outer query.
Comments
Post a Comment