Using MySql, can I sort a column but have 0 come last?

前端 未结 4 648
说谎
说谎 2020-12-24 05:38

I want to sort by an column of ints ascending, but I want 0 to come last. Is there anyway to do this in MySql?

相关标签:
4条回答
  • 2020-12-24 05:50

    You may want to try the following:

    SELECT * FROM your_table ORDER BY your_field = 0, your_field;
    

    Test case:

    CREATE TABLE list (a int);
    
    INSERT INTO list VALUES (0);
    INSERT INTO list VALUES (0);
    INSERT INTO list VALUES (0);
    INSERT INTO list VALUES (1);
    INSERT INTO list VALUES (2);
    INSERT INTO list VALUES (3);
    INSERT INTO list VALUES (4);
    INSERT INTO list VALUES (5);
    

    Result:

    SELECT * FROM list ORDER BY a = 0, a;
    
    +------+
    | a    |
    +------+
    |    1 |
    |    2 |
    |    3 |
    |    4 |
    |    5 |
    |    0 |
    |    0 |
    |    0 |
    +------+
    8 rows in set (0.00 sec)
    
    0 讨论(0)
  • 2020-12-24 05:55

    The following query should do the trick.

    (SELECT * FROM table WHERE num!=0 ORDER BY num) UNION (SELECT * FROM table WHERE num=0)
    
    0 讨论(0)
  • 2020-12-24 05:56
    SELECT * FROM your_table ORDER BY 0.1/your_field;
    
    0 讨论(0)
  • 2020-12-24 06:03

    You can do the following:

    SELECT value, IF (value = 0, NULL, value) as sort_order
    FROM table
    ORDER BY sort_order DESC
    

    Null values will be down of the list.

    0 讨论(0)
提交回复
热议问题