我试图从我们的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的计数是什么,因为Occurences的这个值不正确?我想通过指定COUNT(
engine4_blog_blogs .
owner_id )
它只会计算该字段 - 我还必须补充一点,列字段owner_id
仅存在于engine4_blog_blogs表中。
现在我尝试了各种排列,包括JOINS,INNER JOINS和LEFT JOINS,并且都产生相同的结果......不正确的计数()。
基本上我正在寻找这个输出:
username / Occurences / owner_id / storage_path
jack91 / 10 / 4 / (public/user/1f/001f_250b.JPG)
有谁知道我做错了什么(请记住我10多年来没有触及过sql)?谢谢你的帮助!
答案 0 :(得分:1)
我发表评论作为答案。
您正在计算owner_id。但应该算上他的帖子。 所以,而不是
COUNT( `owner_id` ) AS Occurences
做
COUNT(DISTINCT engine4_blog_blogs.blog_id)
假设blog_id
是engine4_blog_blogs
答案 1 :(得分:0)
正确分组 。您必须按所有非聚合列进行分组:
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支持非标准分组语法 - 如果您坚持使用标准,它将按预期工作。