背景
在日常使用数据库的过程中,无论是你日常的查询提数,还是产品封装的SQL查询做页面展示,都避免不了数据排序,既然遇到排序,就避免不了中文排序以及自定义序列排序,一般的默认排序是按照MySQL默认的字符集排序,直接order by 后面跟排序字段是不能满足业务需求的mysql排序,那在MySQL中是如何解决这一问题的呢?
一、中文排序
默认排序,经如下图分析,很明显不是按照中文拼音排序的
select?name?from( select?'王五'?as?name? union select?'张三'?as?name? union select?'李四'?as?name? union select?'赵六'?as?name?)a order?by?name?asc
解决方案:我们通过convert函数将name字段值转换为unicode编码,然后再进行排序,就能达到我们的目的
select?name?from( select?'王五'?as?name? union select?'张三'?as?name? union select?'李四'?as?name? union select?'赵六'?as?name?)a order?by?convert(name?using?gbk)?asc
二、自定义中文排序
问题场景:假设一个班有四个同学,张三、李四、王五、赵六,现在我们想要统计四位同学的成绩,一般逻辑是按照总分升序或者降序即可,但是需求变了,我想按照赵六-李四-张三-王五这样的来进行排序,该如何做的?
数据准备
with?student?as?( select?'赵六'?as?name,302?as?score? union select?'李四'?as?name?,531?as?score union select?'张三'?as?name?,207?as?score union select?'王五'?as?name?,459?as?score) select?*?from?student

解决方案:由于自定义排序的数组是已经确定的,我们可以利用给确定的排序数组从小到大进行编号,然后关联主表,按照编号进行升序即可
注:排序的解决方案可以参考我的历史文章:
with?student?as?( select?'赵六'?as?name,302?as?score? union select?'李四'?as?name?,531?as?score union select?'张三'?as?name?,207?as?score union select?'王五'?as?name?,459?as?score)
select?t1.*?from?student?t1?inner?join (select?name, ????(case?when?name='王五'?then?1 ???????when?name='张三'?then?2 ???????when?name='赵六'?then?3 ???????when?name='李四'?then?4 ?????end)?as?rk from?student)t2 on?t1.name?=?t2.name order?by?rk?asc

总结
本篇文章主要解决了MySQL中文排序和中文自定义排序问题,涉及的知识点是convert函数的数据类型转换,case when条件表达式以及连接查询的使用.
(编辑:老爷爷站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|