2013-06-05 36 views
3

數據庫具有表personsMySQL的rowrank基於ORDER BY 2列

id   int 
points  int 
voted_on int 
other columns 

我想知道哪一行秩與id x具有相關,具有相同點行具有相同的行級別的行。此查詢的偉大工程和快速(但告訴我,如果你知道更好的:)

select count(*) 
from persons p cross join 
    (select points from persons p where p.id = x) const 
where p.points > const.points; 

但現在我想升級的查詢人較少voted_on,不過分的相同數量的,有一個更好的排比排名更高的人排名。然而,具有相同數量的點和voted_on的人應該具有相同的行等級。

回答

1

你需要一個更復雜的where條款:

select count(*) 
from persons p cross join 
    (select points, voted_on from persons p where p.id = x) const 
where (p.points > const.points) or 
     (p.points = const.points and p.voted_on >= const.voted_on) 

我不知道,如果「更好」是指低等級或更高等級。如果voted_on更大,這會給予更高的等級。對於較低的等級,請將>=更改爲<=

編輯:

我相信這個工程的「最低」行排名(根據您的評論):

select count(*) + 1 
from persons p cross join 
    (select points, voted_on from persons p where p.id = x) const 
where (p.points > const.points) or 
     (p.points = const.points and p.voted_on > const.voted_on) 

這將在「1」而不是「0」開始的排名。

+0

非常感謝你的回答,但是我寧願給他們所有最高的排名,上面的查詢給出了所有3最低的排名。如果數據庫中有6個人,並且2到4個人的點數和voted_on相同,那麼他們的所有rowrank是2還是4(而不是4)。再次感謝和抱歉,應該說過這個。並且你的查詢是否想要(id,voted_on)上的索引? –

+0

感謝編輯,作爲魅力工作,最後一個問題:我需要一個額外的索引來加速它嗎?目前只有(id,points)。 –

+0

@KevinVermaat。 。 。 'points,voted_on'上的索引可能會有幫助,就像'id'上的索引(用於子查詢)一樣。如果您需要多個「x」的值,請提出另一個問題。這個問題可能會有非常不同的解決方案。 –