MySQL自然订购的产品名称

时间:2015-01-22 11:27:46

标签: mysql

我在标题栏中有一个包含以下内容的表

a short name
z short name
Oase AquaMax ECO Premium 10000 Pump
Oase AquaMax ECO Premium 12000 Pump
Oase AquaMax ECO Premium 16000 Pump
Oase AquaMax ECO Premium 4000 Pump
Oase AquaMax ECO Premium 6000 Pump
Oase AquaMax ECO Premium 8000 Pump

我需要按照您希望的方式订购这些产品,如下所示

a short name
Oase AquaMax ECO Premium 4000 Pump
Oase AquaMax ECO Premium 6000 Pump
Oase AquaMax ECO Premium 8000 Pump
Oase AquaMax ECO Premium 10000 Pump
Oase AquaMax ECO Premium 12000 Pump
Oase AquaMax ECO Premium 16000 Pump
z short name

但是当我这样做时:

select `title` from `products` order by `title` ASC

它们按此顺序出现。

a short name
Oase AquaMax ECO Premium 10000 Pump
Oase AquaMax ECO Premium 12000 Pump
Oase AquaMax ECO Premium 16000 Pump
Oase AquaMax ECO Premium 4000 Pump
Oase AquaMax ECO Premium 6000 Pump
Oase AquaMax ECO Premium 8000 Pump
z short name

我也尝试过:

select `title` from `products` order by `title` + 0 ASC

但是这又做了同样的事情,如何克服这个问题以便它们以正确的顺序出现?

3 个答案:

答案 0 :(得分:0)

尝试

select title from products order by length(title),title ASC

并且不要在表和字段名称周围使用单引号。

答案 1 :(得分:0)

您可以使用此查询将标题列转换为ASC顺序:

SELECT title
FROM temp
ORDER BY CONVERT( SUBSTRING( title, 26, 9 ) , UNSIGNEDINTEGER ) 

答案 2 :(得分:0)

所以主要的问题是你的字符串中有一个整数,并且你想在查询中将它用作二级排序。

在这里,问题是MySQL不仅仅支持你从字符串中提取那个数字(正则表达式在这里很好,正如本question所讨论的那样)。另一种解决方案可能是,尝试查找第一个数字(locate)的位置,因为它显示为here

如果标题中最多只有一个数字,则以下查询有效:

SELECT s FROM
  -- this subselect returns positions for the first number in the title
  (SELECT *, LEAST( 
    if (LOCATE('0',title)>0,LOCATE('0',title),999),
    if (LOCATE('1',title)>0,LOCATE('1',title),999),
    if (LOCATE('2',title)>0,LOCATE('2',title),999),
    if (LOCATE('3',title)>0,LOCATE('3',title),999),
    if (LOCATE('4',title)>0,LOCATE('4',title),999),
    if (LOCATE('5',title)>0,LOCATE('5',title),999),
    if (LOCATE('6',title)>0,LOCATE('6',title),999),
    if (LOCATE('7',title)>0,LOCATE('7',title),999),
    if (LOCATE('8',title)>0,LOCATE('8',title),999),
    if (LOCATE('9',title)>0,LOCATE('9',title),999)
  ) AS firstint_pos FROM products) AS t
ORDER BY
  -- first order by the string before the integer value
  IF (firstint_pos<999, SUBSTR(title,1, firstint_pos), s),
  -- then order by the integer value
  CONVERT(SUBSTR(title, firstint_pos), SIGNED);

或者您可以在表格中添加一种sortno列并对其进行维护......