我有一个表,其中持有职位的状态。表列为:
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