我目前在我的网站上使用django-voting。但事实证明,当投票数量.Vote.objects.counts()达到10,000时,这个查询很慢(1.03秒)并出现在mysql-slow.log中
# Query_time: 1.031839 Lock_time: 0.000069 Rows_sent: 1 Rows_examined: 72754
SET timestamp=1363621528;
SELECT (COALESCE(SUM(vote), 0)) AS `score`, (COALESCE(COUNT(vote), 0)) AS `num_votes` FROM `votes` WHERE (`votes`.`object_id` = 10136 AND `votes`.`content_type_id` = 48 ) LIMIT 1;
我想知道是否有更好的方法来实现这一目标?
答案 0 :(得分:1)
您应该通过mysql客户端查看该表votes
,然后执行explain select:
EXPLAIN SELECT (COALESCE(SUM(vote), 0)) AS `score`, (COALESCE(COUNT(vote), 0)) AS `num_votes` FROM `votes` WHERE (`votes`.`object_id` = 10136 AND `votes`.`content_type_id` = 48 ) LIMIT 1;
然后检查列表'vote'是否在此查询期间被编入索引,如果没有 - 您应该在'vote'列上添加新索引。