MySQL: Order by field, placing empty cells at end

前端 未结 2 1782
故里飘歌
故里飘歌 2020-12-13 05:50

I have a MySQL table which contains a number of products. What I want to do is sort the table by one particular column (most of the values begin with numbers for example: 1s

相关标签:
2条回答
  • 2020-12-13 06:33
    select * from table
    order by if(field = '' or field is null,1,0),field
    
    0 讨论(0)
  • 2020-12-13 06:38

    This is one of the most effective method

    ASC Order

    SELECT * FROM user ORDER BY name IS NULL, name ASC
    

    Expected Result:

    +----+--------+------------+
    | id |  name  | date_login |
    +----+--------+------------+
    |  3 |  david | 2016-12-24 |
    |  2 |  john  | NULL       |
    |  4 |  zayne | 2017-03-02 |
    |  1 |  NULL  | 2017-03-12 |
    

    DESC Order

    SELECT * FROM user ORDER BY name IS NULL, name DESC
    

    Expected Result:

    +----+--------+------------+
    | id |  name  | date_login |
    +----+--------+------------+
    |  4 |  zayne | 2017-03-02 |
    |  2 |  john  | NULL       |
    |  3 |  david | 2016-12-24 |
    |  1 |  NULL  | 2017-03-12 |
    
    0 讨论(0)
提交回复
热议问题