我正在尝试对包含字母、数字和引号的字段进行排序,但我无法按顺序获得结果。表中的字段(名为name)的数据如下所示,尽管没有按如下所示进行排序:
6"w x 9"h
6"w x 10"h
7"w x 8"h
7"w x 9"h
7"w x 10"h
7"w x 21"h
10"w x 10"h我使用的命令是
select name from my_table order by name;结果是
10"w x 10"h
6"w x 10"h
6"w x 9"h
7"w x 10"h
7"w x 21"h
7"w x 8"h
7"w x 9"h 我已经尝试了我在这个网站上找到的所有以下内容。我根本不能让最后一个运行起来,但是其他的运行得比上面的要好一些,但仍然不正确。
order by name * 1
order by name + 0
order by CAST(name AS DECIMAL(10,2))
order by length(name), name
order by CAST(SUBSTR(name, 0, LOCATE('w', name) - 1) AS int),
CAST(SUBSTR(name FROM (LOCATE('h', name) - 1)) AS int)上面的前两个备选方案给出了这个输出,所以他们几乎就是这样做的。
6"w x 9"h
6"w x 10"h
7"w x 10"h
7"w x 21"h
7"w x 9"h
7"w x 8"h
10"w x 10"h 有没有人知道如何对它们进行排序,使它们按正确的顺序排列,如下所示。
6"w x 9"h
6"w x 10"h
7"w x 8"h
7"w x 9"h
7"w x 10"h
7"w x 21"h
10"w x 10"h 发布于 2019-04-13 01:49:04
最后一个方向是正确的。您需要按字符串中的数字排序:
ORDER BY CAST(SUBSTR(name, 1, LOCATE('"w', name) - 1) AS signed),
CAST(SUBSTR(name, LOCATE('x', name) + 1, LOCATE('"h', name) - LOCATE('x', name) -1) AS signed)发布于 2019-04-13 01:59:24
在MySQL 8.x中,您可以使用REGEXP_SUBSTR()函数来提取可变长度的复杂表达式:
select dimension
from (
select
dimension
cast(regexp_substr(dimension, '[0-9]+') as int) as w,
cast(substr(regexp_substr(dimension, 'x +[0-9]+'), 3, 10) as int) as h
from t
)
order by w, hhttps://stackoverflow.com/questions/55656743
复制相似问题