如何在 MySQL 中按任意关键字排序?
mysqlmysqli database
为此,请使用 ORDER BY FIELD() ASC。让我们首先创建一个表 −
mysql> create table DemoTable(Title varchar(100)); Query OK, 0 rows affected (0.56 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('Java'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('C'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('Python'); Query OK, 1 row affected (0.63 sec) mysql> insert into DemoTable values('MongoDB'); Query OK, 1 row affected (0.20 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+---------+ | Title | +---------+ | Java | | C | | Python | | MongoDB | +---------+ 4 rows in set (0.00 sec)
以下是按任意关键字排序的查询 −
mysql> select *from DemoTable order by FIELD(Title,'MongoDB,C,Python,Java') ASC;
这将产生以下输出 −
+---------+ | Title | +---------+ | Java | | C | | Python | | MongoDB | +---------+ 4 rows in set (0.00 sec)