問題描述:有一個業務表,其狀態值有以下幾種
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) asc;
輸出結果:
按照后面的值正序排列,無匹配的將會放在最前面(比如2)
倒序時候,依據值最前面的值的匹配行的放在最后面,無匹配狀態值將作為狀態值列表的最前面的狀態值(2)對應匹配行放在最后面