需要帮助获取多篇文章的类别

时间:2016-01-21 20:51:01

标签: mysql sql

我正在尝试用PHP开发知识库系统。我试图返回有1个或更多帖子的类别。我有以下SQL代码:

SELECT `category_id`, `category_name` FROM `categories` WHERE(SELECT 
`category_id` FROM `posts` HAVING COUNT(`posts`.`post_id`) >= 1) ORDER BY 
`category_id` ASC

我尝试了,我得到了所有类别,而不仅仅是其中包含超过1个帖子的类别。我不确定问题是什么。请帮忙

3 个答案:

答案 0 :(得分:1)

#1:>1代替>=1

#2:您计算所有帖子,而不是每个类别的帖子。切换到相关子查询或更好:

SELECT `category_id`, `category_name` 
FROM `categories` AS c 
JOIN 
 ( SELECT `category_id` 
   FROM `posts`
   GROUP BY category_id 
   HAVING COUNT(`posts`.`post_id`) > 1
) AS p
ON c.category_id = p.category_id 
ORDER BY `category_id` ASC

答案 1 :(得分:1)

如果您想要 1个或更多帖子,则只需INNER JOINcategories之间的简单posts即可。这只会返回两个表中都存在category_id的行,这意味着该类别至少有一个帖子。

SELECT DISTINCT c.category_id, c.category_name
FROM categories AS c
JOIN posts AS p ON c.category_id = p.category_id

如果您确实需要超过1个的类别,则可以使用GROUP BYCOUNT(*)

SELECT c.category_id, c.category_name
FROM categories AS c
JOIN posts AS p ON c.category_id = p.category_id
GROUP BY c.category_id
HAVING COUNT(*) > 1

答案 2 :(得分:0)

您缺少在where语句中使用哪个列:

SELECT `category_id`, `category_name` FROM `categories` WHERE category_id in 
(SELECT `category_id` FROM `posts` HAVING COUNT(`posts`.`post_id`) >= 1) 
ORDER BY `category_id` ASC