栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

MySQL wrong results with GROUP BY and ORDER BY

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MySQL wrong results with GROUP BY and ORDER BY

This is your query:

SELECt *FROM (SELECt *      FROM user_comission_configuration_history      ORDER BY on_date DESC     ) AS ordered_historyWHERe user_id = 408002GROUP BY comission_id;

One major problem with your query is that it uses a MySQL extension to

groupby
that MySQL explicitly warns against. The extension is the use of other
columns in the in the
select
that are not in the
group by
or in aggregation
functions. The warning (here) is:

MySQL extends the use of GROUP BY so that the select list can refer to
nonaggregated columns not named in the GROUP BY clause. This means that the
preceding query is legal in MySQL. You can use this feature to get better
performance by avoiding unnecessary column sorting and grouping. However,
this is useful primarily when all values in each nonaggregated column not
named in the GROUP BY are the same for each group. The server is free to
choose any value from each group, so unless they are the same, the values
chosen are indeterminate.

So, the values returned in the columns are indeterminate.

Here is a pretty efficient way to get what you want (with “comission” spelled
correctly in English):

SELECt *FROM user_commission_configuration_history cchWHERe NOT EXISTS (select 1       from user_commission_configuration_history cch2       where cch2.user_id = cch.user_id and  cch2.commission_id = cch.commission_id and  cch2.on_date > cch.on_date      ) AND      cch.user_id = 408002;


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/402283.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号