如何在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)
这是获取所有带有ORDERBY的记录的查询,例如-
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)
热门推荐
10 医院探望朋友祝福语简短
11 毕业祝福语简短女朋友
12 春节虎年爸妈祝福语简短
13 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短