我需要在 PHP/MySQL 中计算属于主类别及其子类别的帖子总数。我有三个表格:
tb_categories
tb_posts
tb_posts_to_categories
现在要获取属于某个类别及其所有子类别的帖子总数,我使用以下代码:
<?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。
但是,当帖子关联到两个不同的父类别或其任何子类别时,代码可以正常工作。仅当帖子与主类别及其多个子类别相关联时才会出现问题。我们如何解决这种错误的计算?请帮助我解决这些问题。谢谢!
最佳答案
试试这个来计算类别中的帖子及其直接子类别。
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
关于php - 统计 PHP MySQL 中属于主要类别和子类别的帖子总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37225614/