共計 2077 個字符,預計需要花費 6 分鐘才能閱讀完成。
本篇文章為大家展示了 MySQL 中怎么按照指定的字段排序,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
測試數據
drop table a;
create table a (x varchar(10),y varchar(10));
insert into a values(yujx , all),(oracle , pc),(mysql , mobile
# 表 a 的測試數據如下
MySQL select * from a;
+——–+——–+
| x | y |
+——–+——–+
| yujx | all |
| oracle | pc |
| mysql | mobile |
+——–+——–+
3 rows in set (0.00 sec)
# 默認的按 y 排序(升序或降序)結果
MySQL select * from a order by y;
+——–+——–+
| x | y |
+——–+——–+
| yujx | all |
| mysql | mobile |
| oracle | pc |
+——–+——–+
3 rows in set (0.00 sec)
MySQL select * from a order by y desc;
+——–+——–+
| x | y |
+——–+——–+
| oracle | pc |
| mysql | mobile |
| yujx | all |
+——–+——–+
3 rows in set (0.00 sec)
現在想按 mobile- all- pc 的順序排序,可使用如下方法
方法一:使用 FIND_IN_SET(str,strlist) 函數
MySQL select * from a order by find_in_set(y, mobile,all,pc
+——–+——–+
| x | y |
+——–+——–+
| mysql | mobile |
| yujx | all |
| oracle | pc |
+——–+——–+
3 rows in set (0.00 sec)
方法二:使用 FIELD(str,str1,str2,str3,…) 函數
#FIELD 函數主要用途會返回值在后面列表中的位置,如下
MySQL select x,y,field(y, mobile , pc , all) sort_Nu from a order by field(y, mobile , pc , all
+——–+——–+———+
| x | y | sort_Nu |
+——–+——–+———+
| mysql | mobile | 1 |
| oracle | pc | 2 |
| yujx | all | 3 |
+——–+——–+———+
3 rows in set (0.00 sec)
方法三:使用 SUBSTRING_INDEX(str,delim,count) 函數
MySQL select * from a order by substring_index(mobile,all,pc ,y,1);
+——–+——–+
| x | y |
+——–+——–+
| mysql | mobile |
| yujx | all |
| oracle | pc |
+——–+——–+
3 rows in set (0.00 sec)
# 看下面 substring_index(mobile,all,pc ,y,1) 取值, 可知按 b 列的值排序 y 的順序固然就是 mobile,all,pc 了
MySQL select y,substring_index(mobile,all,pc ,y,1) b from a;
+——–+————-+
| y | b |
+——–+————-+
| all | mobile, |
| pc | mobile,all, |
| mobile | |
+——–+————-+
3 rows in set (0.00 sec)
方法四:使用 case when
MySQL select x,y,case when y= mobile then 1 when y= all then 2 when y= pc then 3 end sort_nu from a order by case when y= mobile then 1 when y= all then 2 when y= pc then 3 end;
+——–+——–+———+
| x | y | sort_nu |
+——–+——–+———+
| mysql | mobile | 1 |
| yujx | all | 2 |
| oracle | pc | 3 |
+——–+——–+———+
3 rows in set (0.00 sec)
上述內容就是 MySQL 中怎么按照指定的字段排序,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注丸趣 TV 行業資訊頻道。