1. 程式人生 > 實用技巧 >MySQL如何對資料庫狀態值指定排序

MySQL如何對資料庫狀態值指定排序

問題描述:有一個業務表,其狀態值有以下幾種

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');

資料如下:

此時應當使用field函式:

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

輸出結果: