MySql 排序 varchar as int,以字符开头

MySql sort order varchar as int, starting with character

我的数据库中有 'name' 列,客户可以在其中输入以下值:

样本 1、样本 2、样本 101、样本 11、样本 20、样本 100、一些样本、活动样本等

所以,当我想按此列结果排序数据时:

active sample
sample 1
sample 100
sample 101
sample 11
sample 2
sample 20
some sample 

改为

active sample
sample 1
sample 2
sample 11
sample 20
sample 100
sample 101
some sample

所以,数据从不以数字开头,有时以数字结尾,但有时根本不包含数字。 按字母顺序排序很重要,但是当数据包含相同的前缀时,它应该将值排序为 int。

提前致谢。

分解这段极其丑陋的代码...

取初始值,测试是否包含' '字符。如果是,那么我们开始拆分 ' ' 字符的索引,如果否,则只是 return 初始值。为 ' ' 分隔字符串的每个附加可能性开始递归。这是为了允许 2 ' ' 个分隔的单词后跟一个数值,或者视情况而定。

SQL Fiddle 这里:http://sqlfiddle.com/#!2/70168/7

查询:

SELECT 
   sampleInfo,

   IF (LOCATE(' ', sampleInfo) > 0,
       SUBSTRING(sampleInfo, 1, LOCATE(' ', sampleInfo) - 1),
       sampleInfo) AS firstPart,

   IF (LOCATE(' ', sampleInfo) > 0,
       IF (LOCATE(' ', SUBSTRING(sampleInfo, LOCATE(' ', sampleInfo) + 1)) > 0,          
           SUBSTRING(
             SUBSTRING(sampleInfo, LOCATE(' ', sampleInfo) + 1),
             1,
             LOCATE(' ', SUBSTRING(sampleInfo, LOCATE(' ', sampleInfo) + 1)) - 1),
           SUBSTRING(sampleInfo, LOCATE(' ', sampleInfo) + 1)),
           0) AS secondPart,

   IF (LOCATE(' ', sampleInfo) > 0,
       IF (LOCATE(' ', SUBSTRING(sampleInfo, LOCATE(' ', sampleInfo) + 1)) > 0,
           SUBSTRING(
             SUBSTRING(sampleInfo, LOCATE(' ', sampleInfo) + 1),
             LOCATE(' ', SUBSTRING(sampleInfo, LOCATE(' ', sampleInfo) + 1)) + 1),
           0),
       0) AS thirdPart    

FROM test
ORDER BY 
  firstPart,
  thirdPart,
  CONVERT(secondPart, SIGNED) --if conversion fails the value is 0

结果:

╔═══════════════╦═══════════╦════════════╦═══════════╗
║  SAMPLEINFO   ║ FIRSTPART ║ SECONDPART ║ THIRDPART ║
╠═══════════════╬═══════════╬════════════╬═══════════╣
║ asdf 1        ║ asdf      ║ 1          ║         0 ║
║ asdf 2        ║ asdf      ║ 2          ║         0 ║
║ sample        ║ sample    ║ 0          ║         0 ║
║ sample 1      ║ sample    ║ 1          ║         0 ║
║ sample 2      ║ sample    ║ 2          ║         0 ║
║ sample 11     ║ sample    ║ 11         ║         0 ║
║ sample 20     ║ sample    ║ 20         ║         0 ║
║ sample 100    ║ sample    ║ 100        ║         0 ║
║ sample 101    ║ sample    ║ 101        ║         0 ║
║ sample test 1 ║ sample    ║ test       ║         1 ║
║ sample test 2 ║ sample    ║ test       ║         2 ║
╚═══════════════╩═══════════╩════════════╩═══════════╝

免责声明:此解决方案的性能或可扩展性不高。通过使用另一种语言(例如 PHPC# 来完成此 SUBSTRING 工作,您会得到更好的服务,举几个例子。这也会根据您在评论中所说的内容对您的数据做出一些假设。