0

我有三张桌子。类别、主题和帖子。每个主题都有一个外键引用它所属的类别。每个帖子都有一个外键引用它所在的主题。

此查询的目的基本上是作为首页查询。我想要每个类别以及每个类别中的主题数量和帖子数量。这是我的查询,它有效。这是最简单的方法吗?

SELECT      c.*,
            COUNT(t.idCategory) AS tCount,
            p.pCount
FROM        categories AS c
  LEFT JOIN topics AS t
  ON        c.id = t.idCategory
  LEFT JOIN (SELECT      t.idCategory,
                         COUNT(p2.idTopic) AS pCount
             FROM        topics AS t
               LEFT JOIN posts AS p2
               ON        t.id = p2.idTopic
             GROUP BY    t.idCategory) AS p
  ON         c.id = p.idCategory
GROUP BY     t.idCategory
ORDER BY     c.id

谢谢!

4

2 回答 2

1

如果您说的是简单,我想这可能是一个答案:

Select 
      c.*,
      (Select count(*) from topic t where c.id = t.idCategory) as tCount,
      (Select count(*) from posts p join topics t2 on t2.id = p.idTopic where c.id = t2.idCategory) as pCount
From categories c
于 2012-04-18T00:52:18.470 回答
0

您可以先将派生表中的主题和帖子放在一起,然后再加入类别:

SELECT 
    c.id,
    COUNT(tp.id) AS TotalTopics,
    tp.TotalPosts
FROM categories AS c
    LEFT JOIN (
        SELECT 
            t.id,
            t.idCategory,
            COUNT(p.id) AS TotalPosts
        FROM topics AS t 
            LEFT JOIN posts AS p ON t.id = p.idTopic
        GROUP BY    
            t.id,
            t.idCategory) AS tp ON c.id = tp.idCategory
GROUP BY 
    c.id,
    tp.TotalPosts
ORDER BY c.id
于 2012-04-18T01:16:22.850 回答