QQ 咨询
谢谢打赏
微信交流
432

MySQL如何做如等级/成色等特殊顺序的排序
时间: 2020-12-17 10:02:09  作者:北桥苏  阅读:(25)
 

前言:

       在涉及商品类的项目时,为了给同一类商品定位,往往会分等级或者成色。而等级/成色有时是用类似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,但还是有区别,具体的后期补上,拜拜。






用户登录


     QQ登录

我的标签


随机文章

  • MySQL表分区的选择与实践小结 在一些系统中有时某张表会出现百万或者千万的…… 查看详情
  • 淘客分销,订单追踪解决方案(1). 提前创建好pid 1万个插入数据库…… 查看详情
  • PHP高并发高负载下的3种实战场景解决方法在实际开发项目中,产品一旦推广开来,总能遇到…… 查看详情

友情链接





Copyright© 2016-2021 北桥苏 & 版权所有    赣ICP备16002525号-1
如有侵权、不妥之处,请联系站长的客服并出示版权证明以便删除。敬请谅解! 站长客服联系方式:QQ2652364582