gpt4 book ai didi

sql - 基于 where 子句选择范围

转载 作者:行者123 更新时间:2023-11-29 14:10:33 25 4
gpt4 key购买 nike

有这样一张 table

id | user | message
___________________
0 | dan | ...
1 | john | ...
2 | dan | ...
3 | dan | ...
4 | john | ...
(and so on)

如何从id之前的100条消息到id之后的100条消息中选择dan的消息?如果我只是根据 id 列 +/- 100 选择,则不能保证两边都是 100,因为其他用户的消息可能会妨碍。我想 SELECT * from table WHERE user = 'dan' and (some clause here) order by id;

数据库是Postgresql

最佳答案

嗯。 . . union all 怎么样:

(select m.*
from messages m
where user = 'dan' and id < $id
order by id desc
limit 100
) union all
(select m.*
from messages m
where user = 'dan' and id > $id
order by id asc
limit 100
)
order by id;

这对于 (user, id) 上的索引甚至应该相当有效。

关于sql - 基于 where 子句选择范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37166819/

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