我怎样才能按数字,长度和数字对SQL进行排序信吗?

时间:2016-09-30 09:44:22

标签: mysql sorting

我应该如何排序SELECT

示例列表

1, 2, 2A, 4, 10, 10A

SQL

$query = "SELECT * FROM table WHERE column1 = '$var' ORDER BY length(column2), column2";

如果我ORDER BY length()喜欢我的例子,那么2A将会落在最底层 如果我删除length(),则会在1之后删除。

如何排序,如上所示?

3 个答案:

答案 0 :(得分:0)

像这样:

$query = "SELECT * FROM table WHERE column1 = '$var' ORDER BY CAST(column2 as UNSIGNED), column2";

答案 1 :(得分:0)

按十六进制排序是最好的方法:

$query = "SELECT *, cast(hex(column2 as unsigned) as l FROM table WHERE column1 = '$var' ORDER BY l";

答案 2 :(得分:0)

使用alphas找到here等自定义功能,您可以先输入值的数字部分,然后输入值的字符串部分。

如果您定义并填充表格:

CREATE TABLE test (t VARCHAR(255));
INSERT INTO test VALUES
  ('10A'),
  ('2'),
  ('2A'),
  ('4'),
  ('10'),
  ('1');

然后创建一个名为alphas的自定义函数,它提取字符串部分(无数字):

DELIMITER |
DROP FUNCTION IF EXISTS alphas; 
CREATE FUNCTION alphas( str CHAR(32) ) RETURNS CHAR(16) 
BEGIN 
  DECLARE i, len SMALLINT DEFAULT 1; 
  DECLARE ret CHAR(32) DEFAULT ''; 
  DECLARE c CHAR(1); 
  SET len = CHAR_LENGTH( str ); 
  REPEAT 
    BEGIN 
      SET c = MID( str, i, 1 ); 
      IF c REGEXP '[[:alpha:]]' THEN 
        SET ret=CONCAT(ret,c); 
      END IF; 
      SET i = i + 1; 
    END; 
  UNTIL i > len END REPEAT; 
  RETURN ret; 
END | 
DELIMITER ;

然后你可以这样做一个有序的查询:

SELECT t FROM test ORDER BY CAST(t AS UNSIGNED), alphas(t);

CAST函数会将10A等字符串转换为无符号数10