我有一个简单的问题:
我有一个 postgresql
表:Scores(score integer)
。
我怎样才能最快地获得最高的 10 分?
更新:
我将多次执行此查询,并以最快的解决方案为目标。
explain analyze
在哪里?
为此,您可以使用 limit
select *
from scores
order by score desc
limit 10
如果性能很重要(什么时候不重要;-)寻找分数指数。
从 8.4 版开始,您还可以使用标准 (SQL:2008) fetch first
select *
from scores
order by score desc
fetch first 10 rows only
正如@Raphvanns 指出的那样,这会给你 first 10 rows
字面意思。要删除重复值,您必须选择 distinct
行,例如
select distinct *
from scores
order by score desc
fetch first 10 rows only
似乎您正在使用 LIMIT 子句以 DESC
结束顺序寻找 ORDER BY
:
SELECT
*
FROM
scores
ORDER BY score DESC
LIMIT 10
当然 SELECT *
可能会严重影响性能,因此请谨慎使用。
请注意,如果前 10 个值存在关联,您将仅获得前 10 行,而不是前 10 个 values 提供的答案。例如:如果前 5 个值是 10、11、12、13、14、15,但您的数据包含 10、10、11、12、13、14、15,那么您只会得到 10、10、11、12、13、 14 作为您的前 5 名,带有 LIMIT
这是一个解决方案,如果存在平局,它将返回超过 10 行,但您将获得 some_value_column
在技术上位于前 10 名的所有行。
select
*
from
(select
*,
rank() over (order by some_value_column desc) as my_rank
from mytable) subquery
where my_rank <= 10
(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date DESC
LIMIT 10)
UNION ALL
(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date ASC
LIMIT 10)
fetch first X rows only
是我一直在寻找的答案——从遥远的未来感谢您!