mysql混合计数来自几个表

时间:2012-03-29 09:09:41

标签: mysql

我正在尝试实现主题总数,帖子总数以及给定部分的上一篇文章,请查找数据库结构和查询如下...

fcats

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

ftopics

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

fposts

| id | post  | topic_id | posted_by
+----+-------+----------+---------+
|  1 | post  | 1        | user    |
+----+-------+----------+---------+

当前查询

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

通过使用上面的查询,我只能获得给定部分的total_topics,但我对如何获得帖子总数和给定部分的最后一篇文章感到困惑。请帮助,谢谢。

3 个答案:

答案 0 :(得分:1)

对于答案的第一部分,你应该使用count distinct,第二部分是subquery:

SELECT c.id, 
       c.title ,
       count( distinct t.cat_id) AS total_topics ,
       count( distinct p.id) AS total_posts ,
       (select p2.id 
        from ne_forum_posts p2
        inner join ne_forum_topics t2 on p2.topic_id = t2.id
        inner join ne_forum_sub_cats c2 on c2.id = t2.cat_id
        where c2.id = c.id
        order by p2.id desc 
        limit 1) as last_post_id    
FROM   ne_forum_sub_cats c LEFT OUTER JOIN
       ne_forum_topics t on  c.id = t.cat_id LEFT OUTER JOIN
       ne_forum_posts p on p.topic_id = t.id
WHERE  section = "gd"

所有拼写错误已修复并经过测试。

答案 1 :(得分:1)

也许是这样的:

SELECT 
    id, 
    title ,
    (
        SELECT 
            count(ftopics.id) 
        FROM 
            ftopics 
        WHERE 
            ftopics.cat_id = fcats.id
    ) AS total_topics,
    (
        SELECT
            COUNT(distinct fposts.id)
        FROM
            ftopics
            JOIN fposts
                ON ftopics.id=fposts.topic_id
        WHERE 
            ftopics.cat_id = fcats.id
    ),
    (
       select 
         fposts.id 
       from fposts
       inner join ftopics on fposts.topic_id = ftopics.id
       inner join fcats c2 on c2.id = ftopics.cat_id
       where fcats.id = c2.id
       order by fposts.id desc 
       limit 1
    ) as last_post_id 
FROM   fcats 
WHERE  section = "gd"

答案 2 :(得分:1)

SELECT  A.id section_id, 
        IFNULL(COUNT(DISTINCT B.id),0) topics_count, 
        IFNULL(COUNT(C.id),0) post_count, 
        (SELECT post from fposts where id = MAX(C.id)) last_post
FROM    fsections A LEFT JOIN ftopics B    
ON      A.id = B.cat_id    
LEFT    JOIN fposts C    
ON      C.topic_id = B.id    
WHERE   A.section = "gd"
GROUP   BY A.id

还包括该部分的空案例没有任何帖子