sql自定义排序问题

如果需要对查询结果自定义排序,可以使用order by case语句,我们都非常熟悉了,举例如下:

drop table if exists  `Teacher`;
create table Teacher(TID varchar(10),Tname nvarchar(10));
insert into Teacher values('01' , '张三');
insert into Teacher values('02' , '李四');
insert into Teacher values('03' , '王五');

select * from `Teacher`
    order by case `Tname` 
        when '张三' then '1'
        when '李四' then '2'
        when '王五' then '3' end;

上述查询结果没有任何问题,如我们想要实现的一样。

如果自定义排序的项目超过10个,还是按照上述序号从"1"排到"10"的话,结果会怎样呢?

drop table if exists  `Teacher`;
create table Teacher(TID varchar(10),Tname nvarchar(10));
insert into Teacher values('01' , '王一');
insert into Teacher values('02' , '王二');
insert into Teacher values('03' , '王三');
insert into Teacher values('04' , '王四');
insert into Teacher values('05' , '王五');
insert into Teacher values('06' , '王六');
insert into Teacher values('07' , '王七');
insert into Teacher values('08' , '王八');
insert into Teacher values('09' , '王九');
insert into Teacher values('10' , '王十');

select * from `Teacher`
    order by case `Tname` 
        when '王一' then '1'
        when '王二' then '2'
        when '王三' then '3'
        when '王四' then '4'
        when '王五' then '5'
        when '王六' then '6'
        when '王七' then '7'
        when '王八' then '8'
        when '王九' then '9'
        when '王十' then '10' end;

然后我们会发现,想要排到第"10"位的项目总会串到第2个,在"1"之后,"2"之前,这是什么原因呢?

其实,我们在设置序号的时候,应按照"01" "02" "03"至"10"的形式(类似在电脑里按照名称对文件/文件夹进行排序),现在我们来试一下

drop table if exists  `Teacher`;
create table Teacher(TID varchar(10),Tname nvarchar(10));
insert into Teacher values('01' , '王一');
insert into Teacher values('02' , '王二');
insert into Teacher values('03' , '王三');
insert into Teacher values('04' , '王四');
insert into Teacher values('05' , '王五');
insert into Teacher values('06' , '王六');
insert into Teacher values('07' , '王七');
insert into Teacher values('08' , '王八');
insert into Teacher values('09' , '王九');
insert into Teacher values('10' , '王十');

select * from `Teacher`
    order by case `Tname` 
        when '王一' then '01'
        when '王二' then '02'
        when '王三' then '03'
        when '王四' then '04'
        when '王五' then '05'
        when '王六' then '06'
        when '王七' then '07'
        when '王八' then '08'
        when '王九' then '09'
        when '王十' then '10' end;

这次运行结果就没有任何问题了,如下:

PS:如果自定义排序超过100个,需按照"001" "002" "003"直至"099" "100",不过在实际情况中,很少有自定义排序的项目超过100个的情况吧。

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