mysql order by 错误,MySQL错误的结果与GROUP BY和ORDER BY

I have a table user_comission_configuration_history and I need to select the last Comissions configuration from a user_id.

Tuples:

eeddf4dfa6c685a8a6f756c19c7504cc.png

I'm trying with many queries, but, the results are wrong. My last SQL:

SELECT *

FROM(

SELECT * FROM user_comission_configuration_history

ORDER BY on_date DESC

) AS ordered_history

WHERE user_id = 408002

GROUP BY comission_id

The result of above query is:

e6b75ca50e2b7b36067254494cde3829.png

But, the correct result is:

id user_id comission_id value type on_date

24 408002 12 0,01 PERCENTUAL 2014-07-23 10:45:42

23 408002 4 0,03 CURRENCY 2014-07-23 10:45:41

21 408002 6 0,015 PERCENTUAL 2014-07-23 10:45:18

What is wrong in my SQL?

解决方案

This is your query:

SELECT *

FROM (SELECT *

FROM user_comission_configuration_history

ORDER BY on_date DESC

) AS ordered_history

WHERE user_id = 408002

GROUP BY comission_id;

One major problem with your query is that it uses a MySQL extension to group by that MySQL explicitly warns against. The extension is the use of other columns in the in theselect 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 cch

WHERE 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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值