mysql sql语句求优化 [code=SQL]SELECT tid,count(*) as count FROM `pw_posts` WHERE fid=77 GROUP BY tid ORDER BY count DESC LIMIT 10 [/code] 其中tid ,fid分别有建了索引,表里有160万条数据,速度挺慢的,用explain显示如下 SIMPLEpw_posts reffid fid 2 const 38112 Using where; Using temporary; Using filesort
[解决办法]
[解决办法] 语句本身没有问题,但是设计可以改善
你应该先缓存数据 INSERT INTO `pw_posts_stat`(tid, fid, count) SELECT tid, fid, count(*) as count FROM `pw_posts` GROUP BY tid, fid
然后每次查询的时候就会很快了 SELECT tid, count FROM `pw_posts_stat` WHERE fid=77 ORDER BY count DESC LIMIT 10 SELECT tid, count FROM `pw_posts_stat` WHERE fid=77 ORDER BY count DESC LIMIT 11, 10
SELECT tid, count FROM `pw_posts_stat` WHERE fid=66 ORDER BY count DESC LIMIT 10