我有以下 MySQL 查询,它似乎消耗了过多的系统 CPU 处理器时间。
假设查询得到上周评论数最多的新闻:
$timeago = strtotime("-1 week");
$query = "SELECT * ,
news.id,
news.title,
news.state,
news.date,
COUNT(comments.module_id) as comments_count,
comments.module,
comments.state
FROM news
LEFT OUTER JOIN comments on comments.module_id = news.id AND comments.module = 'news' AND comments.state = '1'
WHERE news.state = '2'
GROUP BY news.id, news.title, news.date
ORDER BY news.date >= $timeago DESC, comments_count DESC limit 6";
$result = mysql_query($query) or die (mysql_error());
$data = mysql_fetch_assoc($result);
query servers me 恰到好处,它整理出上周评论数最多的新闻。 news表中有17290条记录。出于这个原因,我试图找出一种对 CPU 消耗有益的方式来修复查询。
欢迎提出任何建议。
解释计划说
|编号 |选择类型 |表 |类型 |可能的键 | key | key 长度 |引用 |行 |额外的
| 1 |简单 |新闻 |引用 |状态 |状态 | 4 |常量 | 17282 |在哪里使用;使用临时的;使用文件排序
| 1 |简单 |评论 |引用 |模块编号 |模块编号 | 101 | saidasea_v2.news.id,常量,常量 | 4
最佳答案
尝试将您的查询更改为:
SELECT * ,
news.id,
news.title,
news.state,
news.date,
COUNT(comments.module_id) as comments_count,
comments.module,
comments.state
FROM news
LEFT OUTER JOIN comments on comments.module_id = news.id
WHERE news.state = '2'
AND comments.module = 'news' AND comments.state = '1'
GROUP BY news.id, news.title, news.date
ORDER BY news.date >= $timeago DESC, comments_count DESC limit 6
此外,如果您只需要带有评论的新闻,请使用inner join
而不是left outer join
。
关于MySQL 查询消耗了过多的系统 CPU 处理器时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13237570/