最快的MySQL排名大表

时间:2013-05-21 17:52:20

标签: php mysql sql database

信息:我有这张桌子( PERSONS ):

PERSON_ID   int(10)
POINTS      int(6)
4 OTHER COLUMNS which are of type int(5 or 6)

该表由25M行组成,每天增长0.25M。点的分布约为0到300点,表的85%有0点。

问题:如果他们得到至少1分,我想回到他/她所具有的等级的用户。在 SQL PHP 组合中,如何以及在哪里以最快的方式执行此操作?

额外信息:这些查询每100秒就会发生一次。到目前为止我看到的解决方案还不够快,如果需要更多信息,请询问。

欢迎任何建议,因为您了解我是PHP和MySQL的新手:)

2 个答案:

答案 0 :(得分:3)

t(points)t(person_id, points)上创建索引。然后运行以下查询:

select count(*)
from persons p
where p.points >= (select points from persons p where p.person_id = <particular person>)

子查询应该使用第二个索引作为查找。第一个应该是第一个索引的索引扫描。

有时MySQL对优化有点奇怪。所以,这实际上可能更好:

select count(*)
from persons p cross join
     (select points from persons p where p.person_id = <particular person>) const
where p.points > const.points;

这只是确保给定人的点的查找发生一次,而不是每行。

答案 1 :(得分:1)

  1. Partition您的桌子分为两个分区 - 一个用于0分的人,另一个用于有一个或多个分的人。
  2. 在您的表上添加一个索引,在person_id上添加另一个索引(如果这些索引尚不存在)。
  3. 要查找特定人员的密集排名,请运行查询:

    select count(distinct p2.points)+1
    from person p1
    join person p2 on p2.points > p1.points
    where p1.person_id = ?
    

    要查找特定人员的非密集排名,请运行查询:

    select count(*)
    from person p1
    join person p2 on p2.points >= p1.points
    where p1.person_id = ?
    

    (我希望密集排名查询运行得更快。)