dshdsh2016 2015-05-21 12:54
浏览 141
已采纳

MySQL按一个列排序,该列具有由斜杠分隔的多个数值

I have a table (policy_details) which has column 'notenumber' with values:

150/1  
150/2  
150/1/2  
150/2/1  

I need the resultset shown below using query order by notenumber asc

150/1  
150/1/2  
150/2  
150/2/1  

I have tried:

select *,REPLACE(notenumber, N'/', N'') AS newnotenumber 
from policy_details 
order by newnotenumber asc;

I need to fetch notenumber in ascending order.

  • 写回答

1条回答 默认 最新

  • duan7772 2015-05-21 13:31
    关注

    Far and away the best solution is to redesign your schema to store each part of notenumber in a different field. Barring this, you need to split out each part of notenumber, convert it to a numeric type, and order by it. You'll have to add a clause to the order by for each part you split out, there's no way around that.

    Example:

    select
      notenumber,
      replace(substring(substring_index(notenumber, '/', 1), length(substring_index(notenumber, '/', 1 - 1)) + 1), '/', ''),
      replace(substring(substring_index(notenumber, '/', 2), length(substring_index(notenumber, '/', 2 - 1)) + 1), '/', ''),
      replace(substring(substring_index(notenumber, '/', 3), length(substring_index(notenumber, '/', 3 - 1)) + 1), '/', '')
    from test
    order by
      convert(replace(substring(substring_index(notenumber, '/', 1), length(substring_index(notenumber, '/', 1 - 1)) + 1), '/', ''), signed integer),
      convert(replace(substring(substring_index(notenumber, '/', 2), length(substring_index(notenumber, '/', 2 - 1)) + 1), '/', ''), signed integer),
      convert(replace(substring(substring_index(notenumber, '/', 3), length(substring_index(notenumber, '/', 3 - 1)) + 1), '/', ''), signed integer)
    ;
    

    Note you'll need to insert the index number of the split part twice into each replace clause.

    SQL fiddle for the above solution: http://sqlfiddle.com/#!9/dc935/1/0

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程