我有 table
Users (user_id integer, user_name string, scores integer)
该表将包含 1-6 百万条记录。在 user_name 和 scores
上有indexes用户将输入他的名字,我应该向他显示该表中的一页,按分数排序,将包含他和其他用户。
我在 2 个查询中完成:
首先:
select user_id from (
select row_number() over (order by scores desc),
user_id
from users
where user_name="name" limit 1
)
第二:
select * from users limit 20 offset The_User_Id/20+1
我得到的页面包含我的用户和其他用户。
但是当用户在有数百万条记录的表中间时,我有偏移量 500000,工作很慢,大约 1-2 秒,如何改进它?
最佳答案
偏移量本身会使您的查询变慢。 如果不需要纯sql,可以用编程语言形成查询,何不考虑Paging Through Results ?按 user_id 对第二个查询进行排序,并将分页需求限制为 20,而不是使用偏移量。
关于postgresql - 优化 select 中的大偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22367095/