我正在尝试对包含字母,数字和引号的字段进行排序,但我无法按顺序获得结果。表中的字段(命名名称)具有这样的数据,但未按所示顺序排序:
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
最后一个是正确的方向。您需要按字符串中的数字排序:
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)
在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, h