计算PHP MySQL中属于主要类别和子类别的总帖子数

时间:2016-05-14 10:40:50

标签: php mysql

我需要计算属于主要类别的帖子总数及其在PHP / MySQL中的子类别。我有三个表格:

tb_categories

enter image description here

tb_posts

enter image description here

tb_posts_to_categories

enter image description here

现在要获取属于某个类别及其所有子类别的帖子总数,我使用以下代码:

<?php
include("includes/db-config.php");

// Create connection
$connection = @mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME) 
or die(mysqli_connect_error());

    // Get total number of posts in a category
    function get_post_counts($category_id)
    {
        global $connection;
        $category_to_post = array();

        // Build database query
        $sql = "SELECT COUNT(`post_id`) AS `post_count`, `category_id` FROM `tb_posts_to_categories`  GROUP BY `category_id`";

        // Execute database query
        $rs = mysqli_query($connection, $sql);
        while($row = mysqli_fetch_assoc($rs))
        {
            $category_to_post[$row['category_id']] = $row['post_count']; 
        }

        // Build database query
        $sql2 = "SELECT `category_id`, `category_parent` FROM `tb_categories` WHERE `category_parent` <> 0";

        // Execute database query
        $rs2 = mysqli_query($connection, $sql2);

        while($row2 = mysqli_fetch_assoc($rs2))
        {
            $category_to_post[$row2['category_parent']] += $category_to_post[$row2['category_id']]; 
        }

        return $category_to_post[$category_id];
    }

$total_posts = get_post_counts(2);

echo $total_posts;

?>

输出

11

但是这个输出不正确。它应该等于8.但是如果你提供子类别id,那么输出是正确的。只有在为函数提供父类别ID时才会搞乱。

因为我有一对多的关系。可以将帖子分配给多个类别甚至子类别。与两个以上类别(一个主要类别及其子类别)相关联的帖子将再次计算,从而产生结果11而不是8。

但是,当帖子与两个不同的父类别或其任何子类别相关联时,代码可以正常工作。问题仅在帖子与主要类别及其多个子类别相关联时。我们如何解决这种错误的计算?请帮帮我这个家伙。谢谢!

1 个答案:

答案 0 :(得分:2)

尝试使用此功能计算类别中的帖子及其直接子类别。

SELECT COUNT(DISTINCT post_id)
FROM (
  (SELECT post_id
  FROM tb_posts_to_categories
  WHERE category_id = 2)
  UNION ALL
  (SELECT pc.post_id
  FROM tb_posts_to_categories pc
    JOIN tb_categories c ON pc.category_id = c.category_id
  WHERE c.category_parent = 2)
) AS t

这是另一个较小的变种:-) 但是,如果WHERE包含OR条件,MySQL有时会被索引使用。

SELECT COUNT(DISTINCT pc.post_id)
FROM tb_posts_to_categories pc
  JOIN tb_categories c ON pc.category_id = c.category_id
WHERE c.category_parent = 2 OR c.category_id = 2