我有一个表categories
和表posts
。我想返回超过3个帖子的类别。
我的查询
SELECT `categories`.`category_title`, COUNT(posts.post_id) as total_posts
FROM (`categories`)
JOIN `posts` ON `posts`.`category_id` = `categories`.`category_id`
HAVING `total_posts` > 3
ORDER BY `categories`.`date_created` desc
它只返回1行。在不使用2个查询的情况下执行此类查询的正确方法是什么?
答案 0 :(得分:3)
您的查询正在使用名为“隐藏列”的MySQL功能,您可能甚至不知道它。这是因为您的查询引用了一些元素,例如date_created,这些元素应该聚合但不是(“应该”表示根据SQL标准和大多数其他数据库)。
您的查询存在的问题是它缺少分组。另一种编写方法是使用子查询中的聚合,在加入类别之前:
SELECT `categories`.`category_title`, total_posts
FROM `categories` JOIN
(select categoryid, COUNT(posts.post_id) as total_posts
from `posts`
group by categoryid
having count(*) > 3
) pc
ON `pc`.`category_id` = `categories`.`category_id`
ORDER BY `categories`.`date_created` desc
答案 1 :(得分:2)
您需要按类别group
项目。
SELECT `categories`.`category_title`, COUNT(posts.post_id) as total_posts
FROM (`categories`)
JOIN `posts` ON `posts`.`category_id` = `categories`.`category_id`
GROUP BY `categories`.`category_id`
HAVING `total_posts` > 3
ORDER BY `categories`.`date_created` desc