在项目中整理档口部分模块时,发现了一个方法
/**
* 获取门店下最大的code
* @param storeId
* @return
* @throws Exception
*/
ScmStall findMaxCode(String storeId) throws Exception;
sql 为:
<select id="findMaxCode" parameterType="java.lang.String" resultType="com.choice.scm.entity.scm.ScmStall">
select * from scm_stall s where s.store_id = #{storeId}
and s.delete_flag = 0 order by cast(s.stall_code as SIGNED ) desc limit 1
</select>
使用了cast函数将编码转为了整数,然后使用排序取最大值,当时看到了这种方法非常好奇,因为编码可能会存非数字,他也能转化吗,他的排序规则是什么?
在sql中写了个查询看了一眼
select depot_code, CAST(depot_code AS signed) from scm_depot ORDER BY CAST(depot_code AS signed) DESC;
结果展示:
我们可以看到,正常的数字被成功转换,转换的规则为从第一个非0的开始转换;
验证了刚才的猜想
字母开头的都被转换为了0;
我们修改一串数字,将56565656改为了56565e56,再次执行
总结,cast函数转换规则:从左到右,从0索引处,到第一个非数字处,中间的部分,会被转为整数,默认为0;