Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimize SQL-query

Tags:

sql

php

mysql

I have following query:

Select diary_id, 
   (select count(*) 
    from `comments` as c 
    where c.d_id = d.diary_id) as diary_comments 
From `diaries` as d

It takes long time (near 0.119415 in my case). How to make it faster?

I see only one way: Doing additional query for comment number for each row from my main query. But it will be something like doing queries in cycle. Something like:

while ($r = mysql_fetch_array($res))
{
   $comments = mysql_query("select count(*) from `comments` where d_id = ".$r['diary_id']);
}

I think this is a bad strategy. Any other advice?

like image 652
user52005 Avatar asked Dec 23 '22 12:12

user52005


2 Answers

SELECT d.diary_id, count(c.d_id) as diary_comments 
FROM diaries d
LEFT OUTER JOIN comments c ON (d.diary_id = c.d_id)
GROUP BY d.diary_id

I seem to have been downvoted because you can actually retreive all the data needed from just the diaries table. I assumed that this was a simplified example and in reality other fields from the diaries table would be required, also this method brings back records which have no comments. If you don't need any of these two things then I would go with the other answer.

like image 189
Tom Haigh Avatar answered Jan 02 '23 23:01

Tom Haigh


It looks like you have all the data you need in the comments table, so I don't see a reason for the join or subquery.

SELECT d_id AS diary_id, COUNT(*) AS diary_comments
FROM `comments`
GROUP BY d_id
like image 27
Ben Hoffstein Avatar answered Jan 02 '23 23:01

Ben Hoffstein