I have the following MySQL query which seems to be consuming an inordinate amount of processor time of the system’s CPU.
The query is suppose to get the news that has the highest number of comments in last week:
$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);
The query servers me just right, it sorts out the news which has the highest number of comments in the last week. There is 17,290 record in news table. For this reason I am try to figure out to fix the query in a way that would be healthy for the CPU consumption.
Any suggestions would be welcome.
Explain plan says
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
| 1 | SIMPLE | news | ref | state | state | 4 | const | 17282 | Using where; Using temporary; Using filesort
| 1 | SIMPLE | comments | ref | module_id | module_id | 101 | saidasea_v2.news.id,const,const | 4
Try changing your query to this:
Also, if you just need to news with comments on it, use
inner joininstead ofleft outer join.