常用mysql排序

mysql中对字符串排序,字符串中有数字有汉字,想按数字的大小来进行排序。仅仅用order by排序,效果不是想要的。

因为字符串排序是先比较字符串第一个字符的大小。而不是像int型比较整个数字的大小。要想用字符串数据排成整型排序的效果,可以采用如下三种方式:

select id,dict_name,type_code from t_dictionary  where type_code='GRADE' ORDER BY `dict_name`*1;  

select id,dict_name,type_code from t_dictionary  where type_code='GRADE' ORDER BY dict_name+0;  

select id,dict_name,type_code from t_dictionary  where type_code='GRADE' ORDER BY CAST(dict_name AS DECIMAL);

但是当你需要排序的字符串为这样的时间格式12:25的时候,好像就有点不太适合上边的方法了,这时候就需要用到这个函数了

select id,dict_name,type_code from t_dictionary  where type_code='GRADE' ORDER BY  TIME_TO_SEC(dict_name);

这样首先将时间字符串转化为整型的秒数,在进行排序。


猜你喜欢

转载自blog.csdn.net/weixin_38728964/article/details/81001926