如何在MySQL中按订单排序?

如要在MySQL中排序,请使用case语句。语法如下-

SELECT *FROM yourTableName
   ORDER BY CASE
   WHEN yourColumnName like '%yourPatternValue1%' then 1
   WHEN yourColumnName like '%yourPatternValue2%' then 2
else 3
end;

为了理解上述语法,让我们创建一个表。创建表的查询如下-

mysql> create table OrderByLikeDemo
   -> (
   -> Id int,
   -> Name varchar(100)
   -> );

使用insert命令在表中插入一些记录。查询如下-

mysql> insert into OrderByLikeDemo values(100,'John Smith');

mysql> insert into OrderByLikeDemo values(101,'Carol Taylor');

mysql> insert into OrderByLikeDemo values(102,'David Miller');

mysql> insert into OrderByLikeDemo values(103,'Mike Taylor');

mysql> insert into OrderByLikeDemo values(104,'Bob Miller');

mysql> insert into OrderByLikeDemo values(105,'Sam Williams');

使用select语句显示表中的所有记录。查询如下-

mysql> select *from OrderByLikeDemo;

以下是输出-

+------+--------------+
| Id   | Name         |
+------+--------------+
| 100  | John Smith   |
| 101  | Carol Taylor |
| 102  | David Miller |
| 103  | Mike Taylor  |
| 104  | Bob Miller   |
| 105  | Sam Williams |
+------+--------------+
6 rows in set (0.00 sec)

这是获取所有带有ORDER BY的记录的查询,例如-

mysql> select *from OrderByLikeDemo
   -> order by case
   -> when Name like '%Taylor%' then 1
   -> when Name like '%Miller%' then 2
   -> else 3
   -> end;

以下是输出-

+------+--------------+
| Id   | Name         |
+------+--------------+
| 101  | Carol Taylor |
| 103  | Mike Taylor  |
| 102  | David Miller |
| 104  | Bob Miller   |
| 100  | John Smith   |
| 105  | Sam Williams |
+------+--------------+
6 rows in set (0.00 sec)