我有三张桌子。类别、主题和帖子。每个主题都有一个外键引用它所属的类别。每个帖子都有一个外键引用它所在的主题。
此查询的目的基本上是作为首页查询。我想要每个类别以及每个类别中的主题数量和帖子数量。这是我的查询,它有效。这是最简单的方法吗?
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
谢谢!