要查询mysql查询

时间:2012-03-26 21:00:29

标签: mysql

我正在进行sql查询以从db,db结构获取值,如下所示......

fcats

| id | title  | section |
+----+--------+---------+
|  1 | test   | gd      |
+----+--------+---------+

ftopics

| id | title  | cat_id  |
+----+--------+---------+
|  1 | test1  | 1       |
+----+--------+---------+

fposts

| id | post  | topic_id |
+----+-------+----------+
|  1 | post  | 1        |
+----+-------+----------+

我希望获得给定类别的主题和帖子总数,并使用以下查询...

SELECT id, title (SELECT count(id) FROM ftopics WHERE cat_id = id) AS total_topics FROM fcats WHERE section = "gd"

并且它为总主题提供了正确的结果但是如何获得所有类别的帖子总数,我很高兴,请帮我写这个查询。感谢。

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT
    t.id,
    t.title,
    COUNT(f.id) + COUNT(p.id) AS total
FROM fcats t
LEFT OUTER JOIN ftopics f
    ON f.cat_id = t.id
LEFT OUTER JOIN fposts p
    ON p.cat_id = t.id
WHERE t.section = "gd"
GROUP BY t.id, t.title

答案 1 :(得分:0)

SELECT
    t.id,
    t.title,
COUNT(f.id) AS total_topics,
(SELECT COUNT(p.id) FROM fposts WHERE topic_id = t.id) total_posts
FROM fcats t
INNER JOIN ftopics f
    ON f.cat_id = t.id

WHERE t.section = "gd"
GROUP BY t.id, t.title

不确定这是否是正确的语法,更新其他答案代码以尝试回答您对这两个总计的请求。