2011-02-26 52 views
0

我想查詢我的大型MYSQL數據庫用戶,找到最常見的名字並對它們進行排名。我也希望能夠顯示當前用戶的名字排名。我想出了一個解決方案,但似乎有點慢。我想知道是否有更快的方法來做到這一點。在MYSQL中最常見的名字更快的排名

這是我想出的查詢。

SELECT rank,fname 
    FROM (SELECT @rownum:[email protected]+1 rank,fname 
     FROM (SELECT fname,count(*) 
     FROM userlist GROUP BY fname 
     ORDER BY count(*) DESC) AS R1 
    JOIN (SELECT @rownum:=0) AS I) AS R2 
WHERE fname = 'Username' 

回答

1

爲了以這種方式

select count(*) + 1 as rank from 
    (select count(*) as number from userlist group by fname having number > 
     (select count(*) as number from userlist where fname='Username') order by number desc) as tab; 

編輯獲得排名一個特定的名字嘗試。如果您想要顯示名稱,請添加用戶變量:

set @name = 'nick'; 
select @name as fname,count(*) + 1 as rank from 
    (select count(*) as number from userlist group by fname having number > 
     (select count(*) as number from userlist where [email protected]) order by number desc) as tab; 
+0

這很完美。第一次運行時速度快23%,第二次運行時只需要0.0001秒(同名)。謝謝 – BigJayMan 2011-02-26 06:06:03