MySQL取出数字字符串的一部分,然后按照数值大小排序

之前做过一张表,表中有个字段是IP,varvhar类型的。所以这样一来ASC或者DESC排序的话是按照字符串的方式排序的。

后来老大提出想要按照IP最后一位的数值大小来排序。

即:例如IP为10.11.12.13,则按照13这一位的数值的大小来排序。


表为manage_mainframe_info,字段为ip_address。

  1. 先把该字段最后一位内容截取出来
  2. 然后转为数字
  3. 然后以其为依据进行排序

select *, (cast (substring_index(ip_address, '.', -1) as unsigned)) as a from manage_mainframe_info order by a desc;

或者

select * from manage_mainframe_info order by (cast (substring_index(ip_address, '.', -1) as unsigned)) desc;


这里有个介绍mysql字符串截取的,挺全的:

http://www.cnblogs.com/zdz8207/p/3765073.html



你可能感兴趣的:(数据库)