COUNT,GROUP BY,INNER JOIN,php,mysql

时间:2012-07-23 13:45:09

标签: php mysql sql aggregate-functions

我目前(正在尝试)开发一个论坛。现在我遇到了一个小障碍。我的数据库里有四张桌子; "类别","论坛","主题"和"回复"。它们都有id,父ID和名字。

我现在的问题是如何存储和获取每个类别和论坛的主题和回复数量。首先,我想到保存每个类别和论坛中的所有主题和回复,以及保存每个主题中的所有回复。

但这是我试图避免看到的东西,因为我必须为每个回复做1x插入和3x更新; 1到类别,1到论坛,1到主题,最后是回复本身,插入。

所以相反,我想如果以某种方式可能(如果是这样的话)用COUNT,GROUP BY和INNER JOIN进行查询

沿线的东西

SELECT * 
  FROM `categories`
  JOIN (COUNT ( * )
         FROM `topics`
     GROUP BY `parent_id`
        WHERE `parent_id` = `categories`.`id`) as `amount_of_topics`
  JOIN (COUNT ( * )
         FROM `topics`
     GROUP BY `parent_id`
        WHERE `parent_id` = `topics`.`id`) as `amount_of_replies`

只是因为我没有按照我想要的方式工作。

因此,要获取所有回复并将其计入特定论坛,连接回复和论坛得到的回复的parent_id属于parent_id属于论坛的主题。

2 个答案:

答案 0 :(得分:3)

我不确定我是否正确理解您的问题,但如果您只是想要特定论坛的主题和回复(如果类别属于论坛而不是相反),您可以使用查询沿着这条线:

SELECT  forums.ID as forum_id
,       forums.name as forum_name
,       Count(topics.ID) AS count_of_topics
,       Count(replies.ID) AS count_of replies
FROM forums 
    LEFT JOIN categories ON forums.ID = categories.parent_id 
    LEFT JOIN topics ON categories.ID = topics.parent_id 
    LEFT JOIN replies ON topics.ID = replies.parent_id
GROUP BY forums.ID, forums.name, categories.ID, categories.name;

如果您正在寻找主题数量&按类别回复,使用:

SELECT  categories.ID as category_id
,       categories.name as category_name
,       Count(topics.ID) AS count_of_topics
,       Count(replies.ID) AS count_of replies
FROM categories
    LEFT JOIN topics ON categories.ID = topics.parent_id 
    LEFT JOIN replies ON topics.ID = replies.parent_id
GROUP BY forums.ID, forums.name, categories.ID, categories.name;

希望有所帮助,但如果这不是您想要实现的目标,请为您的问题添加精确度。

答案 1 :(得分:0)

我认为这是您想要的查询:

SELECT categories.*, `amount_of_topics`, `amount_of_replies`
FROM `categories` JOIN
      (select `parent_id`, COUNT ( * ) as `amount_of_topics` 
       FROM `topics`
       GROUP BY `parent_id`
     )  tp
     on tp.`parent_id` = `categories`.`id`) JOIN
     (select `topics`.`id`) , COUNT ( * ) as `amount_of_replies`
      FROM `topics` 
      GROUP BY `topics`.`id`
    ) ti
    on  tp.`parent_id` = ti.`id`

我们的想法是为您想要的每个主题组创建单独的子查询,然后将它们连接在一起。