Question

SELECT contents.*, 

(SELECT COUNT(*)
FROM comments
WHERE comments.scrap_id = contents.org_scrap_id) AS comment_count

FROM contents
ORDER BY comment_count

this is my intention. but it makes very long waits.

how can i increase the performance of this query?

Was it helpful?

Solution 2

You can increase the performance by creating an index on comments(scrap_id):

create index comments_scrap_id on comments(scrap_id);

You could also try phrasing this as a join and group by:

SELECT co.*, count(com.scrap_id) as comment_count
FROM contents co left outer join
     comments com
     on co.org_scrap_id = com.scrap_id
GROUP BY co.id
---------^ or whatever the appropriate `id` is for this table
ORDER BY comment_count;

But the index is likely to give better performance.

OTHER TIPS

You can rewrite your query using join,but for performance an explain plan is needed,you are using a correlated subquery which will run for each row in contents table and can reduce the performance of query, for below query you need an index for scrap_id from comments table and org_scrap_id from contents table if its not a primary key

SELECT c.*, COUNT(cm.scrap_id) comment_count
LEFT JOIN comments cm
  ON cm.scrap_id = c.org_scrap_id
FROM contents c
GROUP BY c.org_scrap_id
ORDER BY comment_count 

I would suggest you to use joins which would be faster compared to what you are doing now

SELECT contents.*, count(comments.scrap_id) 
from contents 
left outer join comments on comments.scrap_id=contents.scrap_id
group by comments.scrap_id

Thanks.

Please try doing it this way and check if it makes any difference in performance.

  SELECT Conts.* , 
       Comts.scrap_id_COUNT
  FROM
       contents Conts INNER JOIN( SELECT scrap_id , 
                                         COUNT(1) AS scrap_id_COUNT
                                    FROM comments
                                    GROUP BY scrap_id
                                ) AS Comts
       ON Conts.org_scrap_id = Comts.scrap_id
  ORDER BY Comts.scrap_id_COUNT
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top