MYSQL返回另一个表中具有列关系数的行

时间:2012-08-19 20:36:22

标签: php mysql database

我有一个表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个查询的情况下执行此类查询的正确方法是什么?

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