Varchar to number conversion for sorting

前端 未结 5 839
礼貌的吻别
礼貌的吻别 2020-12-05 07:23

I have a query ordered by column:

select * from mytable order by column asc — sort table

column type is varchar,

相关标签:
5条回答
  • 2020-12-05 07:29

    This should work as well:

    
    order by (0 + column) asc
    
    
    0 讨论(0)
  • 2020-12-05 07:30

    Use:

    order by cast(column as unsigned) asc
    
    0 讨论(0)
  • 2020-12-05 07:34
        Added a full code script here , but need to sort 1001 and 1002 before - as well.
    We have total 5 solution , means 5 different queries as solution with full script.
    
    
    =============================================================
        SET NAMES utf8;
        SET foreign_key_checks = 0;
        SET time_zone = 'SYSTEM';
        SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
    
        DROP TABLE IF EXISTS `varchar_sort`;
        CREATE TABLE `varchar_sort` (
          `user_id` int(11) NOT NULL AUTO_INCREMENT,
          `actual_user_id` varchar(200) DEFAULT NULL,
          PRIMARY KEY (`user_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
        INSERT INTO `varchar_sort` (`user_id`, `actual_user_id`) VALUES
        (1, '1001-4'),
        (2, '1001-1'),
        (3, '1001-111'),
        (4, '1002-1'),
        (5, '1001-66'),
        (6, '1001-100'),
        (7, '1001-110');
    
    
        SELECT user_id,actual_user_id,CONVERT(SUBSTRING_INDEX(actual_user_id,'-',-1),UNSIGNED INTEGER) AS num
        FROM varchar_sort
        ORDER BY num;
    
    
        SELECT user_id,actual_user_id
        FROM varchar_sort
        ORDER BY CONVERT(SUBSTRING(actual_user_id, 6), SIGNED INTEGER);
    
    
        SELECT user_id,actual_user_id
        FROM varchar_sort
        ORDER BY CONVERT(SUBSTRING(actual_user_id, LOCATE('-', actual_user_id) + 1), SIGNED INTEGER);
    
    
        SELECT *, CAST(SUBSTRING_INDEX(actual_user_id, '-', -1) AS UNSIGNED) as num FROM varchar_sort ORDER BY num;
    

    select * from varchar_sort order by convert( replace(actual_user_id, '-',''), SIGNED INTEGER ) asc

        **Need to sort 1001 and 1002 as well.**
    
    0 讨论(0)
  • 2020-12-05 07:45

    If we simply modify the order by declaration slightly (add “+0″ to the order by field), you can force MySQL to sort the field naturally.

     > select * from mytable order by column+0 asc;
     column
     1 
     10
     11
     12
     13 
     100
    
    0 讨论(0)
  • 2020-12-05 07:49

    You can use this if you want to treat column as INT only:

    SELECT * FROM mytable ORDER BY column+0;
    1
    10
    11
    12
    13
    100
    

    Or this if you want to treat column as both INT and VARCHAR

    SELECT * FROM mytable ORDER BY column+0, column; #this will sort the column by VARCHAR first and then sort it by INT
    
    abc
    xyz
    1
    10
    11
    12
    13
    100
    
    0 讨论(0)
提交回复
热议问题