MySQL 查询消耗了过多的系统 CPU 处理器时间

标签 mysql sql

我有以下 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/

相关文章:

mysql - 修复表时需要停止mysql吗?

c# - NHibernate/Transaction 如何只提交一个对象而不提交整个 session

php - 传递变量和 php

多个表中分配的 ID 出现的 mysql 计数

c++ - 无法弄清楚这个错误

SQL 服务器 : update primary key after different insert statement

mysql - 如果数字为十进制,sql 查询不起作用

mysql - SQL多表连接 throw 欺骗

c# - 表数据对比-Oracle

php - 我如何在 mysql 中编写 Group By 查询日期时间字段