在 MySQL 中实现自定义排序顺序
要在 MySQL 中实现自定义排序顺序,你需要使用 ORDER BY FIELD()。我们首先创建一个表,代码如下 −
mysql> create table DemoTable -> ( -> Designation varchar(100) -> ); Query OK, 0 rows affected (1.65 sec)
使用 insert 命令向表中插入一些记录,代码如下 −
mysql> insert into DemoTable values('Software Engineer'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Associate Software Engineer'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values('Software Development Engineer'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('Product Manager'); Query OK, 1 row affected (0.17 sec)
使用 select 语句显示表中的所有记录,代码如下 −
mysql> select *from DemoTable;
这会生成以下输出 −
+-------------------------------+ | Designation | +-------------------------------+ | Software Engineer | | Associate Software Engineer | | Software Development Engineer | | Product Manager | +-------------------------------+ 4 rows in set (0.00 sec)
以下是实现 MySQL 中自定义排序顺序的查询 −
mysql> select *from DemoTable -> order by field(Designation,'Associate Software Engineer','Software Engineer','Software Development Engineer','Product Manager');
这会生成以下输出 −
+-------------------------------+ | Designation | +-------------------------------+ | Associate Software Engineer | | Software Engineer | | Software Development Engineer | | Product Manager | +-------------------------------+ 4 rows in set (0.02 sec)
广告