我有一张桌子,上面贴着状态。
表列是:

ID        //which is unique incremental
Post_id   //liked post
user_id   //user who gave like or dislike
type      //"1","0" or "2" which stands for Liked, neutral or disliked.


这是示例数据

+--------+---------+---------+------+
| id     | post_id | user_id | type |
+--------+---------+---------+------+
| 938300 |  347298 |     661 |    0 |
| 938299 |  346185 |       0 |    1 |
| 938298 |  347286 |    2645 |    0 |
| 938297 |  346924 |     374 |    1 |
| 938296 |  347261 |    1523 |    1 |
| 938295 |  347313 |    3233 |    1 |
| 938294 |  346323 |    1375 |    1 |
| 938293 |  347022 |    1779 |    1 |
| 938292 |  347278 |    2645 |    1 |
| 938291 |  347300 |     109 |    1 |
+--------+---------+---------+------+
10 rows in set (0.01 sec)


但是,此查询运行得很完美,但是正如大家所看到的,此表中有数百个数据。我需要的是:

SELECT post_id,
       count(post_id)
FROM   'table'
WHERE  type = '1'
GROUP  BY post_id
ORDER  BY count(post_id)
LIMIT  300;


该查询选择300个最喜欢的帖子,而php代码从中随机选择一个。但是,此查询具有全表扫描,它将持续5秒钟以上。如何加快速度或必须更改表方案?

最佳答案

您可能可以通过使用索引来获得一些加速。您的查询在计算方面是昂贵的,因此缓存可能是更好的答案。查看是否具有这两个索引中的一个或两个对您的表有帮助:

CREATE INDEX post_id_index ON `table` (post_id);
CREATE INDEX type_index ON `table` (type);


如果没有,则使用以下命令删除它们:

DROP INDEX post_id_index ON `table`;
DROP INDEX type_index ON `table`;


如果对他们没有帮助,请确保将其放下,但为确保确定,请事先尝试一下。如果不适合使用缓存,则另一种选择是保留另一个仅保留该结果的表。我认为可能已经有人建议了。我建议使用索引,因为创建索引非常容易。只需将每个命令作为完整的SQL命令运行,然后查看所查询的查询是否更快。这是有关索引的更多信息:

http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

10-07 19:49
查看更多