gpt4 book ai didi

sql查询distinct+其他列

转载 作者:行者123 更新时间:2023-11-29 12:44:35 26 4
gpt4 key购买 nike

比如我有这样一条消息的sql表:

Id   from_user_id   to_user_id    message1    1              2             Hello2    1              2             How are you?3    1              3             Where are you?

并查询 SELECT DISTINCT to_user_id FROM messages;它返回

to_user_id23

但是,这还不够。我需要向其他用户显示 from_user_id(id=1) 的所有最后消息,并避免 N+1 查询问题。结果一定是这样的

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

最佳答案

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;

关于sql查询distinct+其他列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31544320/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com