Home > Backend Development > PHP Tutorial > 求教一个MYSQL数字和字母混合排序问题

求教一个MYSQL数字和字母混合排序问题

WBOY
Release: 2016-06-23 13:48:42
Original
1556 people have browsed it

数据库里有一个表a,表a有一个字段b为字符串类型,里面的数据大多为88A242 ,88A106,88A109,92A129,92A068,2000A291,2000A216,2014A063,2014A315这样的字符串,求教各位大神,如何排序?

排序后应为: 88A106,88A109,88A242,92A068,92A129,2000A216,2000A291,2014A063,2014A315


回复讨论(解决方案)

$s='88A242,88A106,88A109,92A129,92A068,2000A291,2000A216,2014A063,2014A315';$arr=explode(',',$s);natsort($arr);echo "<pre class="brush:php;toolbar:false">";print_r($arr);echo "
Copy after login
";

$str='88A242,88A106,88A109,92A129,92A068,2000A291,2000A216,2014A063,2014A315';$str1=str_replace('A','.',$str);$arr=explode(',',$str1);sort($arr,SORT_NUMERIC);$str2=implode(',',$arr);$str3=str_replace('.','A',$str2);echo $str3;
Copy after login

88A106,88A109,88A242,92A068,92A129,2000A216,2000A291,2014A063,2014A315
Copy after login

不好意思,忘记说明了,因为是从数据库里,所以希望读出来的时候就已经是排好的,而不是需要再用php处理的

那你为什么不排序好后,再存入数据库,无能为力了...

create temporary table T (a varchar(10));insert into T (a) values ('88A242'),('88A106'),('88A109'),('92A129'),('92A068'),('2000A291'),('2000A216'),('2014A063'),('2014A315');select * from T order by lpad(a, 10, '0');
Copy after login
Copy after login
a 88A106 88A109 88A242 92A068 92A129 2000A216 2000A291 2014A063 2014A315 
Copy after login
Copy after login

建议存数据的时候同时存入hash值,查找的时候按照hash排序
至于怎么计算hash值,查查,不难。

create temporary table T (a varchar(10));insert into T (a) values ('88A242'),('88A106'),('88A109'),('92A129'),('92A068'),('2000A291'),('2000A216'),('2014A063'),('2014A315');select * from T order by lpad(a, 10, '0');
Copy after login
Copy after login
a 88A106 88A109 88A242 92A068 92A129 2000A216 2000A291 2014A063 2014A315 
Copy after login
Copy after login



可以啦,求解?,lpad(a, 10, '0')

LPAD(str,len,padstr) 
返回字符串 str, 其左边由字符串padstr 填补到len 字符长度。假如str 的长度大于len, 则返回值被缩短至 len 字符。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template