我对 SQL 相当陌生,正在解决一些实践问题。我有一个示例 Twitter 数据库,我试图根据关注者的数量在每个位置找到前 3 名用户。
这是我正在使用的表格:
id_follower_location
id | followers | location
-----------------+-----------+----------
id28929238 | 1 | Toronto
id289292338 | 1 | California
id2892923838 | 2 | Rome
.
.
locations
location
----------------------
Bay Area, California
London
Nashville, TN
.
.
我已经能够通过以下方式找到“顶级”用户:
create view top1id as
select location,
(select id_followers_location.id from id_followers_location
where id_followers_location.location = locations.location
order by followers desc limit 1
) as id
from locations;
create view top1 as
select location, id,
(select followers from id_followers_location
where id_followers_location.id = top1id.id
) as followers
from top1id;
我能够想出解决这个问题的唯一方法是找出“Top 1st”、“Top 2nd”、“Top 3rd”,然后union
将它们组合起来。这是正确/唯一的方法吗?或者,还有更好的方法?