MySql varchar排序

时间:2013-01-29 13:42:14

标签: mysql sorting varchar

我有另一个问题与其他问题完全相同。我阅读了很多论坛和相关内容,但无法找到答案。我正在使用LPAD,因为我的需求得到了最接近的结果,但它仍然不是我想要的。

ORDER BY LPAD(`my_value`, '500', '0') ASC

记录现在看起来像这样:

Mova 16
Mova 110
Mova 125
Mova 140
Mova 180
Mova 160N

但我按此顺序需要它们:

Mova 16
Mova 110
Mova 125
Mova 140
Mova 160N
Mova 180

那么,我该如何实现呢?

我必须注意,此表中还有其他记录,例如:

"GIACOMINI" R780 DN15 v/2 kampinis
"GIACOMINI" R780 DN20 v/3 kampinis
"GIACOMINI" R780 DN25 v/1 kampinis

还有更多......那些也适合这种情况。

2 个答案:

答案 0 :(得分:1)

这个怎么样?

SELECT   *
FROM     yourtable
ORDER BY CAST(SUBSTRING(yourcolumn,LOCATE(' ',yourcolumn)+1) AS SIGNED) ASC;

结果:

| YOURCOLUMN |
--------------
|    Mova 16 |
|   Mova 110 |
|   Mova 125 |
|   Mova 140 |
|  Mova 160N |
|   Mova 180 |

答案 1 :(得分:1)

我的想法是将您的列转换为固定长度的字符串,其中字母数字字符和数字以块的形式对齐,例如

Input string                       | aligned string
---------------------------------------------------------------------------------------
Mova 16                            | MOVA......0000000016
Mova 110                           | MOVA......0000000110
Mova 180                           | MOVA......0000000180
Mova 160N                          | MOVA......0000000160N.........
"GIACOMINI" R780 DN15 v/2 kampinis | GIACOMINI.R.........0000000780DN........000..etc.
"GIACOMINI" R780 DN20 v/3 kampinis | GIACOMINI.R.........0000000780DN........000..etc.

然后我们可以使用对齐的字符串对行进行排序,但为了获得结果,我们需要创建一个自定义函数:

DROP FUNCTION IF EXISTS strformat;
SET GLOBAL  log_bin_trust_function_creators=TRUE; 
DELIMITER |
CREATE FUNCTION strformat(str VARCHAR(128))
RETURNS VARCHAR(128)
BEGIN
  DECLARE i INT;
  DECLARE last INT;
  DECLARE curr INT;
  DECLARE res VARCHAR(128);
  DECLARE block VARCHAR(10);

  SET res='';
  SET block='';
  SET i=1;

  IF LENGTH(str) = 0 THEN
    RETURN NULL;
  END IF;

  WHILE i <= LENGTH(str) DO
    SET curr=IF(MID(str, i, 1) RLIKE '[A-Z,a-z]', 1,
                  IF(MID(str, i, 1) RLIKE '[0-9]', 2, 0));

    IF (block='') OR (last=curr) THEN
      SET block = CONCAT(block,
                    IF((curr=1) OR (curr=2), MID(str, i, 1), ''));
    ELSE
      IF last=2 THEN
        SET res = CONCAT(res,
                    REPEAT('0', 10 - LENGTH(block)), block);
      ELSE
        SET res = CONCAT(res,
                    block, REPEAT(' ', 10 - LENGTH(block)));
      END IF;
      SET block = IF((curr=1) OR (curr=2), MID(str, i, 1), '');
    END IF;

    SET last=curr;
    SET i = i + 1;
  END WHILE;

  IF curr=1 THEN
    SET res = CONCAT(res, block, REPEAT(' ', 10 - LENGTH(block)));
  ELSEIF curr=2 THEN
    SET res = CONCAT(res, REPEAT('0', 10 - LENGTH(block)), block);
  END IF;

  RETURN UCASE(res);
END;
|
DELIMITER ;

(此处每个块必须限制为10个字符)。

然后您可以按:

订购
ORDER BY strformat(`my_value`)