MySQL语句中distinct 问题记录:

MySQL语句中distinct 问题记录:

测试过程中遇到一个问题,产品要求是把 pack_code去重按照 created倒序排序,让接口返回,开发提供的SQL是:select DISTINCT(pack_code) from eq_coupon_pack where member_id = '607c62f1e16a4342b0a8c431103d750b' order by created desc;

MySQL语句中distinct 问题记录:

我自己写出的SQL是:

select distinct(pack_code),created from eq_coupon_pack where member_id = '607c62f1e16a4342b0a8c431103d750b' order by created desc;

MySQL语句中distinct 问题记录:

然后发现返回的pack_code 是不一样的,最后对比两句SQL,问题如下:

distinct(pack_code),created 过滤的是pack_code和created两个字段都重复的记录;

但是还是不理解为啥 我查出的是最新的pack_code ,而开发这个语句查询的并不是最新时间的pack_code;

然后又找了SQL执行顺序,发现是这样:from > where > group by > select > order by

也就是说先去重最后才排序的,但是这样去重导致的问题是pack_code不是最新时间的;

我的疑问是:MySQL去重是随机取一条记录吗??还是有顺序???