我正在使用PHP和MySQL。
我有$pallet
,它的值如下:
P01
P02
P12
P20
P05
如何将这些值排序为:
P01
P02
P05
P12
P20
答案 0 :(得分:3)
他们都以P
开头吗?如果是这样,您可以sort($pallet)
或执行ORDER BY yourcolumnhere ASC
,因为按字母顺序对它们进行排序就足够了。
答案 1 :(得分:3)
如果值始终以'P'开头,则可以去除'P',将其余部分转换为数字,然后将ORDER BY
转换为ASC。因此:
select yourcolumn
from (
select cast(replace(yourcolumn,'P','') as unsigned) as rank,
yourcolumn from yourtable) t
order by t.rank asc;
修改强>
以下是按字母顺序排序的示例:
create table pallet (id int unsigned not null primary key auto_increment,
pallet varchar(5));
insert into pallet (pallet) values ('P01');
insert into pallet (pallet) values ('P02');
insert into pallet (pallet) values ('P12');
insert into pallet (pallet) values ('P20');
insert into pallet (pallet) values ('P05');
insert into pallet (pallet) values ('P145');
select *
from pallet
order by pallet asc;
结果:
id pallet
-- ------
1 P01
2 P02
3 P05
4 P12
5 P145
6 P20
不完全是我们想要的!
select pallet
from (
select cast(replace(pallet,'P','') as unsigned) as rank,
pallet from pallet) t
order by t.rank asc;
结果:
id pallet
-- ------
1 P01
2 P02
3 P05
4 P12
5 P20
6 P145