MySL实现如等级成色等特殊顺序的排序详解
前言:
在涉及商品类的项目时,为了给同一类商品定位,往往会分等级或者成色。而等级/成色有时是用类似A,A+,A+1,K,L1,L2等英文与数字的组合进行表述。既然是等级,自然就会区分高等级,低等级。有高有低,又给商品定了等级,所以到了商品列表展示,等级排序自然少不了。
项目在开始做的时候关于商品等级字段是直接存储的上面的字母数字,也就是A,A+1之类的。所以在需要以等级排序的时候,以英文字母的方式升序倒序就出现了问题,比如大部分等级中,S是最高级,而英文倒序S排在了后面。
冲突:
直接以英文字母排序很显然是不行的,于是首先想到的是数据表的等级字段改为int,存入数字。在配置里或者单独建一张表与对应数字关联一个等级。类似K对应1之类的,需要升序降序就对数字排序,这样就解决了S排序问题。但是,现实的是商品表的数据量极大,如果要给原来的等级做关联,就要小心的写SQL替换或者手动一个一个改。不知道有没有在不需要修改表的情况下解决那种特殊字符排序的方法,后来还真想到了一个方法。
解决方法:
通过使用MySQL的find_in_set函数,通过自定义的顺序进行排序,所以后续将某个等级提前改动都不会那么被动了,如下示例。
1. 可以先定义升序,倒序的排列
"grade_desc" => ["S","A+","A1","A2","B+1","B+2","B1","B2","C+1","C+2","C1","C2","D+1","D+2","D1","D2","D3","E+1","E+2","E1","E2","F","G+","G1","G2","H+","H1","H2","I+","I1","I2","J+","J","K+","K"]"grade_asc" => ["K","K+","J","J+","I2","I1","I+","H2","H1","H+","G2","G1","G+","F","E2","E1","E+2","E+1","D3","D2","D1","D+2","D+1","C2","C1","C+2","C+1","B2","B1","B+2","B+1","A2","A1","A+","S"]
2. 查询示例
3. ThinkPHP5的使用方式
3.1. 升序
$list = GoodsItem::where('delete_time','=',0) ->field('id,grade') ->orderRaw("find_in_set(grade,'K,K+,J,J+,I2,I1,I+,H2,H1,H+,G2,G1,G+,F,E2,E1,E+2,E+1,D3,D2,D1,D+2,D+1,C2,C1,C+2,C+1,B2,B1,B+2,B+1,A2,A1,A+,S')") ->select(); return $list->toArray();
3.2. 倒序
$list = GoodsItem::where('delete_time','=',0) ->field('id,grade') ->orderRaw("find_in_set(grade,'S,A+,A1,A2,B+1,B+2,B1,B2,C+1,C+2,C1,C2,D+1,D+2,D1,D2,D3,E+1,E+2,E1,E2,F,G+,G1,G2,H+,H1,H2,I+,I1,I2,J+,J,K+,K')") ->select(); return $list->toArray();
3.3.效果
4. find_in_set函数
这个函数可以放在where中使用,查询字段是否存在某个范围内,有点像IN,但还是有区别,具体的后期补上。
以上就是MySQL实现如等级成色等特殊顺序的排序详解的详细内容,更多关于MySQL特殊顺序排序的资料请关注脚本之家其它相关文章!
相关文章
MySQL里Create Index 能否创建主键 Primary Key
MySQL里Create Index 能否创建主键 Primary Key2009-07-07
最新评论