【发布时间】:2020-12-22 19:48:59
【问题描述】:
【问题讨论】:
标签: sql postgresql greatest-n-per-group window-functions
【问题讨论】:
标签: sql postgresql greatest-n-per-group window-functions
最快的方法可能是联合:
(
select c1, c2, count
from the_table
order by count
limit 1
)
union all
(
select c1, c2, count
from the_table
order by count desc
limit 1
)
通常,UNION 中的单个语句不需要括号,但由于我们希望每个语句都有一个 order by,所以它们是必需的。
另一种选择是连接派生表:
select t1.*
from the_table t1
join (
select min(count) as min_count,
max(count) as max_count
from the_table
) mm on t1.count in (mm.min_count, mm.max_count)
但我怀疑这会更快。
【讨论】:
我会推荐窗口函数:
select *
from (
select t.*,
row_number() over(order by count) rn_asc,
row_number() over(order by count desc) rn_desc
from mytable t
) t
where 1 in (rn_asc, rn_desc)
order by count
这需要只扫描一次表(而不是union all 或join)。
【讨论】:
count 上有索引,order by ... limit 1 通常更快。窗口函数需要读取所有值以应用排序。 plan for union plan for derived table plan for window function - 在具有一百万行和count上的索引的表上@