我正试着从mysql db上得到最顶级的博客海报
这目前适用于其中的一部分:
SELECT `username` , COUNT( `owner_id` ) AS Occurences, `owner_id`
FROM `engine4_blog_blogs` , `engine4_users`
WHERE `engine4_users`.`user_id` = `owner_id`
GROUP BY `owner_id`
ORDER BY Occurences DESC
LIMIT 1 它产生:
username / Occurences / owner_id
jack91 / 10 / 4这是正确的。
现在,我需要的是也得到注册的人缩略图图标,所以我尝试如下:
SELECT `username` , COUNT( `engine4_blog_blogs`.`owner_id` ) AS Occurences, `owner_id`, `storage_path`
FROM `engine4_blog_blogs` , `engine4_users`, `engine4_storage_files`
WHERE `engine4_users`.`user_id` = `engine4_blog_blogs`.`owner_id` AND `engine4_users`.`user_id` = `engine4_storage_files`.`user_id`
GROUP BY `engine4_blog_blogs`.`owner_id`
ORDER BY Occurences DESC
LIMIT 1它产生:
username / Occurences / owner_id / storage_path
jack91 / 2480 / 4 / (public/user/1f/001f_250b.JPG)用户名,owner_id & storage_path是正确的,但是由于出现的这个值是不正确的,那么db计数是什么呢?我认为,通过指定COUNT(engine4_blog_blogs.owner_id),它将只计算该字段-而且我还必须添加列字段owner_id只存在于engine4_blog_blogs表中。
现在我尝试了各种排列,包括连接,内部连接和左连接,都产生了相同的结果.不正确的计数()
基本上,我是在寻找这个输出:
username / Occurences / owner_id / storage_path
jack91 / 10 / 4 / (public/user/1f/001f_250b.JPG)有人知道我做错了什么吗(请记住,我已经10年没有接触sql了)?谢谢你的帮助!
发布于 2015-03-17 14:24:48
若要使分组正确工作,请执行以下操作。必须按所有非聚合列分组:
SELECT `username` , COUNT( DISTINCT `engine4_blog_blogs`.`blog_id` ) AS Occurences, `owner_id`, `storage_path`
FROM `engine4_blog_blogs` , `engine4_users`, `engine4_storage_files`
WHERE `engine4_users`.`user_id` = `engine4_blog_blogs`.`owner_id` AND `engine4_users`.`user_id` = `engine4_storage_files`.`user_id`
GROUP BY 1,3,4
ORDER BY Occurences DESC
LIMIT 1您还希望在DISTINCT中添加COUNT()关键字,以获得不同创作的博客数量。
Mysql支持非标准的分组语法--如果您坚持该标准,它将如您所期望的那样工作。
发布于 2015-03-17 14:24:48
我将把我的评论作为回应。
你在数owner_id。但应该算一下他的职位。所以,而不是
COUNT( `owner_id` ) AS Occurences做
COUNT(DISTINCT engine4_blog_blogs.blog_id)假设blog_id是engine4_blog_blogs的主键
https://stackoverflow.com/questions/29101425
复制相似问题