MySQL Order通过特定的字符串?
使用FIELD()
函数通过选择所需的字符串进行排序。语法如下-
SELECT *FROM yourTableName ORDER BY FIELD(yourColumnName,’yourValue1’, ’yourValue2’,’yourValue3’,....N);
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table OrderByListOfStrings -> ( -> Id int not null auto_increment, -> CarName varchar(20), -> PRIMARY KEY(Id) -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into OrderByListOfStrings(CarName) values('Ford'); mysql> insert into OrderByListOfStrings(CarName) values('Audi'); mysql> insert into OrderByListOfStrings(CarName) values('Honda'); mysql> insert into OrderByListOfStrings(CarName) values('Aston Martin'); mysql> insert into OrderByListOfStrings(CarName) values('Bugatti'); mysql> insert into OrderByListOfStrings(CarName) values('BMW');
使用select语句显示表中的所有记录。查询如下-
mysql> select *from OrderByListOfStrings;
以下是输出-
+----+--------------+ | Id | CarName | +----+--------------+ | 1 | Ford | | 2 | Audi | | 3 | Honda | | 4 | Aston Martin | | 5 | Bugatti | | 6 | BMW | +----+--------------+ 6 rows in set (0.00 sec)
这是通过选择字符串来获取顺序的查询。设置任何您想要的顺序-
mysql> select *from OrderByListOfStrings -> order by field(CarName,'Bugatti','BMW','Audi','Aston Martin','Ford','Honda');
以下是重新排列使用field()
方法设置的字符串的输出-
+----+--------------+ | Id | CarName | +----+--------------+ | 5 | Bugatti | | 6 | BMW | | 2 | Audi | | 4 | Aston Martin | | 1 | Ford | | 3 | Honda | +----+--------------+ 6 rows in set (0.00 sec)