我正在尝试用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个帖子的类别。我不确定问题是什么。请帮忙
答案 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 JOIN
和categories
之间的简单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 BY
和COUNT(*)
。
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