简体   繁体   中英

MySQL: How to speed up this query (incl. subqueries)?

The index-page of my forum looks like this:

| Forum   | Topics | Answers |
 ----------------------------
| Forum A | 123    | 45678   | 
| Forum B | 345    | 23128   |
| Forum C | 567    |  2328   | 

Here's my SQL code that works so far but I think there must be a better solution:

SELECT f.`id`, f.`name`, f.`description`, f.`type`, 

      (SELECT COUNT(`id`) 
         FROM threads 
        WHERE `forum_id` = f.`id`) AS num_threads, 

      (SELECT COUNT(p.`id`) 
         FROM threads t, posts p 
        WHERE p.thread_id = t.id 
          AND t.forum_id = f.id) AS num_posts 

  FROM `forums` f ORDER BY `position`

How would you speed up this query? Any alternatives to subqueries?

Thanks in advance!

Learn about SQL joins and GROUP BY :

SELECT   f.id, f.name, f.description, f.type, 
         COUNT(DISTINCT t.id) AS num_threads,
         COUNT(*) AS num_posts
FROM     forums f
    JOIN threads t ON  t.forum_id = f.id
    JOIN posts   p ON p.thread_id = t.id
GROUP BY f.id
ORDER BY f.position

Also, ensure that you have the following indexes:

  • (id) on forums
  • (id, forum_id) on threads
  • (thread_id) on posts

(MySQL will require you to have these indexes if you have created foreign key contraints ).

Something like this, joining the basic select with a couple of subqueries with group by clauses (so they are executed once each, rather than once each per row)

  SELECT f.id, f.name, f.description, f.type, tc.RowCnt, ta.RowCnt
  FROM `forums` f 
  INNER JOIN (SELECT forum_id, COUNT(id) AS RowCnt FROM threads GROUP BY forum_id) tc
  INNER JOIN (SELECT forum_id, COUNT(p.id) AS RowCnt FROM threads t INNER JOIN posts p ON p.thread_id = t.id GROUP BY forum_id) ta
  ORDER BY position

You could likely improve this by doing one of the counts in the main select rather than the subselect (but it is late friday and I am tired!).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM