以下查询返回最多朋友的用户。视图allUserFriendCounts
列出了他们拥有多少朋友的所有用户名(为了我的问题,我需要使用此视图)。运行此查询似乎需要两倍于运行allUserFriendCounts
,因为它必须运行后者两次。
有没有办法更有效地重写这个?
create or replace view getMaxFriendCount(name) as
select f.name
from allUserFriendCounts f
where f.friendcount = (select max(committeecount) from allUserFriendCounts)
GROUP BY name
;
我正在使用PostgreSQL 9.2.1
答案 0 :(得分:1)
如果我理解你,你的初步查询是:
select f.name
from allUserFriendCounts f
where f.friendcount = (select max(c.friendcount) from allUserFriendCounts as c)
group by name
因此您可以使用dense_rank()
或rank()
进行查询:
with cte as (
select
*,
rank() over(order by f.friendcount desc) as rnk
from allUserFriendCounts as f
)
select name
from cte
where rnk = 1
<强> sql fiddle demo 强>