MySQL中的field()函数,可以用来对SQL中查询结果集进行指定顺序排序。

函数使用格式如下:

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

意为:字段str按照字符串str1,str2,str3,str4的顺序返回查询到的结果集。如果表中str字段值不存在于str1,str2,str3,str4中的记录,放在结果集最前面返回。

例:

表数据如下:

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'来排序,结果如下:

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    |
+----+--------+------+-------+

望满足需求。







Logo

更多推荐