该field()
函数返回值在值列表中的索引位置。让我们使用field()
带有ORDER BY的函数对值进行排序。语法如下。
SELECT *FROM yourTableName order by field(yourColumnName,yourValue1,yourValue2,yourValue3,yourValue4,.....N) desc;
为了理解上述语法,让我们首先创建一个表。创建表的查询如下。
mysql> create table OrderByDemo -> ( -> StudentId int -> );
使用insert命令在表中插入一些记录。查询如下。
mysql> insert into OrderByDemo values(101); mysql> insert into OrderByDemo values(1010); mysql> insert into OrderByDemo values(1001); mysql> insert into OrderByDemo values(401);
现在,您可以使用select语句显示表中的所有记录。查询如下。
mysql> select *from OrderByDemo;
以下是输出。
+-----------+ | StudentId | +-----------+ | 101 | | 1010 | | 1001 | | 401 | +-----------+ 4 rows in set (0.00 sec)
这是按值对顺序排序的查询。我们将按降序排序。查询如下。
mysql> select *from OrderByDemo order by field(StudentId,101,401,1001,1010) desc;
以下是输出。
+-----------+ | StudentId | +-----------+ | 1010 | | 1001 | | 401 | | 101 | +-----------+ 4 rows in set (0.00 sec)