0

我正在尝试对包含字母、数字和引号的字段进行排序,但无法按顺序获得结果。表中的字段(命名为名称)具有如下数据,但未按所示排序:

    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 
4

2 回答 2

1

最后一个方向是正确的。您需要按字符串中的数字排序:

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-12T17:49:04.243 回答
0

在 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
于 2019-04-12T17:59:24.127 回答