【发布时间】:2015-04-29 08:16:05
【问题描述】:
当我转到 URL:https://stackoverflow.com/questions?sort=votes 时,StackOverflow 按投票返回问题列表。我知道如何实现这个功能,但我正在寻找“最好的方法”。我将描述一些方法和它们的缺点。
- 只需使用
order by、limit、offset(用于分页)。缺点:如果行数很大,速度会很慢。 - 为
votes列创建索引,并使用order by、limit、offset。缺点:votes可能会经常更改,每次更新一行时,都会重新索引。如果行数很大,limit和offset仍然会变慢。
更多讨论:如果排序功能不仅仅依赖于votes,而是其他列如creationDate、numberOfViews...,以上两种方式都不好。
第一种方式很慢,每次客户端获取有序问题列表,函数f(votes, creationDate, numberOfViews)对每一行计算,然后排序,然后应用panigation,很慢!
第二种方式也不好,因为votes、numberOfViews经常变化,我需要创建一个额外的列fValue来存储预先计算的f(votes, creationDate, numberOfViews)的结果。每次更改 votes 或 numberOfViews 时,我都需要更新此列。另外,如果以后f的功能改了,那就太可怕了!
我正在寻找解决这些问题的最佳方法,希望有人能帮助我。
更新:
架构如下所示:
Question (
id: int primary key auto_increment,
votes: int default 0,
creationDate: timestamp default current_timestamp,
numberOfViews: int default 0
)
选择问题列表:
select *
from Question
order by votes
limit index, 100
如果基于其他列的排序功能:
select *
from Question
order by votes + numberOfViews * 0.96
limit index, 100
或创建新列fValue = votes + numberOfViews * 0.96
select *
from Question
order by fValue
limit index, 100
【问题讨论】:
-
为什么要投反对票?请在这里讨论一些信息!
-
我没有投反对票,但您需要提供更多详细信息。你的问题不能笼统地回答。显示查询、架构、数据、使用情况等。
-
@MarcusAdams:我更新了我的问题。
标签: mysql performance sorting pagination sql-order-by