当前位置: 代码迷 >> PHP >> mysql sql话语求优化
  详细解决方案

mysql sql话语求优化

热度:497   发布时间:2012-09-04 14:19:30.0
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显示如下
SIMPLE pw_posts       ref fid     fid       2     const     38112     Using   where;   Using   temporary;   Using   filesort


------解决方案--------------------
探讨

你这写法更慢呢,子查询查30000多行,然后再对30000多行排序,这不是跑了60000多行么?explain看效率更低引用:

你对结果集分组试试
SELECT tid, COUNT( tid ) AS count FROM (SELECT * FROM `pw_posts` WHERE fid =77) AS ret GROUP BY tid ORDER BY co……

------解决方案--------------------
语句本身没有问题,但是设计可以改善

你应该先缓存数据
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
  相关解决方案