MySQL ORDER BY AVG() DESC not working when certain columns are included

好久不见. 提交于 2019-12-06 04:08:07

Please upgrade to a GA version (5.7.9 was the first; 5.7.18 exists), then test again. IIRC, there was a bug somewhere in this area.

If the bug persists, provide the commands to reproduce the error and submit it to bugs.mysql.com .

I strongly recommend you change from MyISAM to InnoDB. Oracle may throw out the bug report since it involves MyISAM.

Meanwhile, you could see if this gives you the correct ordering:

SELECT  `table1`.`description`, 
        ( SELECT  AVG(`rating` )
            FROM  table2
            WHERE  botid = table1.id 
        ) AS avg_rating
    FROM  `table1`
    ORDER BY  avg_rating DESC 

Provide EXPLAIN FORMAT=JSON SELECT ... for both your version and my version.

Explanation

Your original query appears to have the "inflate-deflate" problem of JOIN ... GROUP BY. First the JOIN gathers more "rows" than you started with, then the GROUP BY shrinks it back to the original number.

My rewrite sticks to the original number of rows (in table1) and probes table 2 for the necessary stuff. Primarily (in this situation) it avoids the tmp table and filesort.

That weird behavior is because of longtext, If you can change your field type to CHAR/VARCHAR it will run perfectly. Or try something like:

SELECT CAST(table1.desc AS CHAR(128)) AS description, AVG( table2.rating ) AS avg_rating FROM table1 LEFT JOIN table2 ON ( table2.botid = table1.id ) GROUP BY table1.id ORDER BY avg_rating DESC;

Working as expected for when run on maria db.Please check your query once because your order by is working on description column instead of avg_rating.

You can also try

SELECT `table1`.`description`, AVG( `table2`.`rating` ) AS avg_rating FROM `table1` LEFT JOIN `table2` ON ( `table2`.`botid` = `table1`.`id` ) GROUP BY `table1`.`id` ORDER BY 2 DESC;

and check the output again.will it remain the same?

Try this one

SELECT *, AVG( table2.rating ) AS avg_rating FROM table1 INNER JOIN table2 WHERE table1.id = table2.botid GROUP BY table1.id ORDER BY table2.rating

give me. feedback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!