MySql排序顺序varchar为int,以字符开头

时间:2015-02-05 15:36:24

标签: mysql sorting int varchar

我有专栏' name'在我的db中,客户端输入的值如下:

样品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。

提前致谢。

1 个答案:

答案 0 :(得分:-1)

打破这段非常难看的代码...

获取初始值并测试它是否包含' '个字符。如果是,那么我们开始拆分该' '字符的索引,如果不是则返回初始值。为' '分隔字符串的每个额外可能性开始递归。这是为了允许2个' '分隔的单词后跟数字值,或者不是视情况而定。

SQL小提琴: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 ║
╚═══════════════╩═══════════╩════════════╩═══════════╝

免责声明:此解决方案不具备高性能或可扩展性。通过SUBSTRINGPHP之类的其他语言执行此C#工作可以获得更好的服务。这也会根据您在评论中所说的内容对您的数据进行一些假设。