如何排序varchar值mysql

j2cgzkjk  于 2021-06-23  发布在  Mysql
关注(0)|答案(3)|浏览(375)

我有一个表,它的id(varchar)是

-----------------------------------------
ID        |NAME    |COLUMN1  |COLUMN2   |
-----------------------------------------
11.10     |abcd    |New col  | new col  |
11.10(a)  |abcd    |New col  | New Col 2|
11.50     |abcd    |New COl  | New coli | 
11.50(a1) |abcd    |New col  | New Col 2|
11.50(a2) |abcd    |New col  | New Col 2|
11.300(a) |abcd    |New col  | New Col 2|
11.200(a) |abcd    |New col  | New Col 2|
11.100(a) |abcd    |New col  | New Col 2|
11.40(a)  |abcd    |New col  | New Col 2|

现在,如果我使用以下方法获取排序数据:

Select * from table order by length(id) asc,id;

我得到的结果是

11.10
11.50
11.10(a)
11.100(a)
11.200(a)
11.300(a)
11.40(a)
11.50(a)
11.50(a1)

但是我想要期望的输出

11.10
11.10(a)
11.40(a)
11.50
11.50(a)
11.50(a2)
11.200(a)
11.300(a)

对于相同的问题,什么是合适的查询?我试过使用cast,但我得到了想要的输出。

sirbozc5

sirbozc51#

Select Convert(Id,UNSIGNED INTEGER) AS num, col1, col2, col3 from Table Order By num 这是甲骨文的to\ u编号,所以我建议它会很有用

qlvxas9a

qlvxas9a2#

您想要的查询可能是:

select ID           
  from Table_
 order by cast( SUBSTRING_INDEX(SUBSTRING_INDEX(id, '.',-1), '(', 1) as signed ),
                SUBSTRING_INDEX(SUBSTRING_INDEX(id, '(',-1), ')', 1);

sql fiddle演示

hsgswve4

hsgswve43#

举个例子,你可以用 length() :

order by length(id), id

更一般的方法是 substring_index() 和隐式转换:

order by substring_index(id, '.', 1) + 0,
         substring_index(id, '.', -1) + 0,
         id

相关问题