MySQL 按特定字符串排序?
使用 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) -> ); Query OK, 0 rows affected (0.68 sec)
使用 insert 命令在表中插入一些记录。查询如下:−
mysql> insert into OrderByListOfStrings(CarName) values('Ford'); Query OK, 1 row affected (0.18 sec) mysql> insert into OrderByListOfStrings(CarName) values('Audi'); Query OK, 1 row affected (0.17 sec) mysql> insert into OrderByListOfStrings(CarName) values('Honda'); Query OK, 1 row affected (0.13 sec) mysql> insert into OrderByListOfStrings(CarName) values('Aston Martin'); Query OK, 1 row affected (0.53 sec) mysql> insert into OrderByListOfStrings(CarName) values('Bugatti'); Query OK, 1 row affected (0.20 sec) mysql> insert into OrderByListOfStrings(CarName) values('BMW'); Query OK, 1 row affected (0.21 sec)
使用 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)
广告