MySQL - SELECT … WHERE id IN (..) 可以用特定列排序吗?
可以使用 field() 函数来使用 SELECT ….WHERE id IN(..) 根据任意列排序。语法如下:-
SELECT *FROM yourTableName WHERE yourColumnName IN(‘value1’,’value2’,.......N) ORDER BY FIELD(yourColumnName,value1’,’value2’,.......N);
为了理解上述语法,我们创建一个表——
mysql> create table SelectOrderbyField -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(30), -> Age int, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.62 sec)
使用 insert 命令在表中插入一些记录。查询如下——
mysql> insert into SelectOrderbyField(Name,Age) values('John',23); Query OK, 1 row affected (0.13 sec) mysql> insert into SelectOrderbyField(Name,Age) values('Carol',25); Query OK, 1 row affected (0.16 sec) mysql> insert into SelectOrderbyField(Name,Age) values('Bob',21); Query OK, 1 row affected (0.15 sec) mysql> insert into SelectOrderbyField(Name,Age) values('Mike',28); Query OK, 1 row affected (0.17 sec) mysql> insert into SelectOrderbyField(Name,Age) values('Sam',26); Query OK, 1 row affected (0.12 sec) mysql> insert into SelectOrderbyField(Name,Age) values('David',23); Query OK, 1 row affected (0.19 sec)
使用 select 语句显示表的所有记录。查询如下——
mysql> select *from SelectOrderbyField;
输出如下——
+----+-------+------+ | Id | Name | Age | +----+-------+------+ | 1 | John | 23 | | 2 | Carol | 25 | | 3 | Bob | 21 | | 4 | Mike | 28 | | 5 | Sam | 26 | | 6 | David | 23 | +----+-------+------+ 6 rows in set (0.00 sec)
以下是使用 order by field() 函数来选择 ...where id in(..) 的查询。
根据 ID 列排序
查询如下——
mysql> select *from SelectOrderbyField where Id IN(5,1,3,2,6,4) -> order by field(Id,5,1,3,2,6,4);
输出如下——
+----+-------+------+ | Id | Name | Age | +----+-------+------+ | 5 | Sam | 26 | | 1 | John | 23 | | 3 | Bob | 21 | | 2 | Carol | 25 | | 6 | David | 23 | | 4 | Mike | 28 | +----+-------+------+ 6 rows in set (0.00 sec)
根据名称列排序
你可以根据名称列进行正确的排序。查询如下——
mysql> select *from SelectOrderbyField where Name IN('Sam','John','Bob','Carol','David','Mike') -> order by field(Name,'Sam','John','Bob','Carol','David','Mike');
输出如下——
+----+-------+------+ | Id | Name | Age | +----+-------+------+ | 5 | Sam | 26 | | 1 | John | 23 | | 3 | Bob | 21 | | 2 | Carol | 25 | | 6 | David | 23 | | 4 | Mike | 28 | +----+-------+------+ 6 rows in set (0.03 sec)
广告