问题描述:有一个业务表,其状态值有以下几种

0:"待审批",1:"通过",2:"不通过",3:"驳回",4:"委托",

我的排序规则既不是 order by status desc 也不是 asc

而是按照  待审批 > 驳回 > 委托 > 通过 >不通过 的顺序排序

CREATE TABLE IF NOT EXISTS `test_process` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`status` int(11) DEFAULT 0,

`statusDesc` varchar(20) DEFAULT '',

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

insert into test_process (status,statusDesc) value (0,'wait_approval');

insert into test_process (status,statusDesc) value (1,'pass');

insert into test_process (status,statusDesc) value (2,'not_pass');

insert into test_process (status,statusDesc) value (3,'callback');

insert into test_process (status,statusDesc) value (4,'entrust');

数据如下:

c58610a6fc2efe0a3ce21c8be738abc7.png

此时应当使用field函数:

select * from test_process order by field(status,0,3,4,1) asc;

输出结果:

78fe68ee678d59cd852adcba1027d5bc.png

按照后面的值正序排列,无匹配的将会放在最前面(比如2)

06b722452c0c4582df1b581bdbf0887c.png

倒序时候,依据值最前面的值的匹配行的放在最后面,无匹配状态值将作为状态值列表的最前面的状态值(2)对应匹配行放在最后面

Logo

一站式 AI 云服务平台

更多推荐