MySQL中 指定字段排序函數field()的用法

MySQL中的field()函數,能夠用來對SQL中查詢結果集進行指定順序排序。函數

函數使用格式以下:.net

 

order by (str,str1,str2,str3,str4……),str與str1,str2,str3,str4比較,其中str指的是字段名字,blog

意爲:字段str按照字符串str1,str2,str3,str4的順序返回查詢到的結果集。若是表中str字段值不存在於str1,str2,str3,str4中的記錄,放在結果集最前面返回。排序

例:字符串

表數據以下:class

root@localhost|iris>select * from ta;
+----+--------+------+-------+
| id | name | age | class |
+----+--------+------+-------+
| 1 | iris | 11 | a1 |
| 2 | iris | 22 | a2 |
| 3 | seiki | 33 | a3 |
| 4 | seiki | 44 | a4 |
| 5 | xuding | 55 | a5 |
| 6 | xut | 66 | a6 |
| 7 | iris | 12 | a2 |
| 8 | iris | 24 | a4 |
| 9 | seiki | 36 | a6 |
| 10 | seiki | 48 | a8 |
| 11 | xuding | 50 | a0 |
| 12 | xut | 77 | a7 |
+----+--------+------+-------+
12 rows in set (0.00 sec)
按照'seiki','iris','xut'來排序,結果以下:select

root@localhost|iris>select * from ta order by field(name,'seiki','iris','xut');
+----+--------+------+-------+
| id | name | age | class |
+----+--------+------+-------+#不在str1,str2,str3中的內容,放在最前面返回,str值相同按照主鍵的順序
| 5 | xuding | 55 | a5 |
| 11 | xuding | 50 | a0 |
| 3 | seiki | 33 | a3 |
| 4 | seiki | 44 | a4 |
| 9 | seiki | 36 | a6 |
| 10 | seiki | 48 | a8 |
| 1 | iris | 11 | a1 |
| 2 | iris | 22 | a2 |
| 7 | iris | 12 | a2 |
| 8 | iris | 24 | a4 |
| 6 | xut | 66 | a6 |
| 12 | xut | 77 | a7 |
+----+--------+------+-------+
12 rows in set (0.00 sec)
按照'seiki','iris'來排序,結果以下:數據

root@localhost|iris>select * from ta order by field(name,'seiki','iris');
+----+--------+------+-------+
| id | name | age | class |
+----+--------+------+-------+#不在str1,str2,str3中的內容,放在最前面返回;str值相同按主鍵順序排列
| 5 | xuding | 55 | a5 |
| 6 | xut | 66 | a6 |
| 11 | xuding | 50 | a0 |
| 12 | xut | 77 | a7 |
| 3 | seiki | 33 | a3 |
| 4 | seiki | 44 | a4 |
| 9 | seiki | 36 | a6 |
| 10 | seiki | 48 | a8 |
| 1 | iris | 11 | a1 |
| 2 | iris | 22 | a2 |
| 7 | iris | 12 | a2 |
| 8 | iris | 24 | a4 |
+----+--------+------+-------+
12 rows in set (0.00 sec)
按照'seiki','iris' desc 來排序,結果以下:查詢

root@localhost|iris>select * from ta order by field(name,'seiki','iris') desc;
+----+--------+------+-------+
| id | name | age | class |
+----+--------+------+-------+
| 1 | iris | 11 | a1 |
| 2 | iris | 22 | a2 |
| 7 | iris | 12 | a2 |
| 8 | iris | 24 | a4 |
| 3 | seiki | 33 | a3 |
| 4 | seiki | 44 | a4 |
| 9 | seiki | 36 | a6 |
| 10 | seiki | 48 | a8 |#倒序時,按照str3,str2,str1的順序逆向排序,
| 5 | xuding | 55 | a5 |#不在str1,str2,str3中的記錄放到最後;str值相同按主鍵順序排列
| 6 | xut | 66 | a6 |
| 11 | xuding | 50 | a0 |
| 12 | xut | 77 | a7 |
+----+--------+------+-------+di

相關文章
相關標籤/搜索