简体   繁体   English

SQL 排序版本数字 + 字符串

[英]SQL Sort verions numeric + string

I have to sort a table by the version column which is a random string + numeric(x.xx.xx).For example my table looks like:我必须按版本列对表进行排序,该列是随机字符串 + 数字(x.xx.xx)。例如,我的表如下所示:

string 1.14.2
string 1.14.1
string 1.14
string 1.14.3
string 1.14.4
string 1.11
string 1.10
string 1.10.2
string 1.9
string 1.9.4
string 1.9.2
string 1.8
string 1.8.8
string 1.4.6

and my result has to look like:我的结果必须看起来像:

string 1.14.4
string 1.14.3
string 1.14.2
string 1.14.1
string 1.11
string 1.10.2
string 1.10
string 1.9.4
string 1.9.2
string 1.9
string 1.8.8
string 1.8
string 1.4.6

my current sql is我目前的 sql 是

SELECT * FROM t_plugins WHERE a_category = 'string' AND a_master_ig = 2
ORDER BY SUBSTRING_INDEX(SUBSTRING_INDEX(trim(a_name), " ", -1), ".", -1)```


Something like this should work:像这样的东西应该工作:

order by
    cast(
        substring_index(
            substring_index(a_name, ' ', -1),
            '.', 
            1
         ) 
         as unsigned
    ) desc,
    cast(
        right(
            substring_index(a_name, ' ', -1),
            length(substring_index(a_name, ' ', -1)) 
                - locate('.', substring_index(a_name, ' ', -1))
        )
        as decimal(10, 5)
    ) desc

The idea is to:这个想法是:

  • separate the string from the version number将字符串与版本号分开

  • isolate the first digit of the version number (and cast it to an integer value) and use it as the first sort criteria隔离版本号的第一个数字(并将其转换为 integer 值)并将其用作第一个排序标准

  • then isolate the second and third part, cast that to a decimal value, and use it as second sort criteria然后隔离第二部分和第三部分,将其转换为十进制值,并将其用作第二个排序标准

Demo on DB Fiddle : DB Fiddle 上的演示

| a_name        |
| :------------ |
| string 1.14.4 |
| string 1.14.3 |
| string 1.14.2 |
| string 1.14.1 |
| string 1.14   |
| string 1.11   |
| string 1.10.2 |
| string 1.10   |
| string 1.9.4  |
| string 1.9.2  |
| string 1.9    |
| string 1.8.8  |
| string 1.8    |
| string 1.4.6  |

I think this is simpler using implicit conversion:我认为使用隐式转换更简单:

order by substring_index(a_name, '.', 1) + 0,
         substring_index(substring_index(a.name, '.', 2), '.', -1) + 0,
         substring_index(a_name, '.', -1) + 0

Assuming there's no space within your "random string", this should give you the result you expect.假设您的“随机字符串”中没有空格,这应该会给您预期的结果。

select 
    *
from 
    your_table
order by 
    cast('/' + TRIM(SUBSTRING(your_version_col,CHARINDEX(' ', your_version_col),LEN(your_version_col)))  + '/' as hierarchyid) desc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM