0

我的论坛的索引页面如下所示:

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

这是我到目前为止有效的 SQL 代码,但我认为必须有更好的解决方案:

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`

你会如何加快这个查询?子查询的任何替代方案?

提前致谢!

4

2 回答 2

2

像这样,将基本选择与带有 group by 子句的几个子查询连接起来(因此它们每个执行一次,而不是每行执行一次)

  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

您可以通过在主选择而不是子选择中进行计数来改善这一点(但现在是星期五晚些时候,我很累!)。

于 2012-11-30T16:57:52.467 回答
2

了解SQL 连接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

此外,请确保您具有以下索引:

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

(如果您创建了外键约束,MySQL 将要求您拥有这些索引)。

于 2012-11-30T16:55:08.117 回答