2013-06-05 34 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”的值,请提出另一个问题。这个问题可能会有非常不同的解决方案。 –