MySQL Orderby a number, Nulls last

前端 未结 12 2526
再見小時候
再見小時候 2020-11-22 16:57

Currently I am doing a very basic OrderBy in my statement.

SELECT * FROM tablename WHERE visible=1 ORDER BY position ASC, id DESC

The probl

相关标签:
12条回答
  • 2020-11-22 17:20

    NULL LAST

    SELECT * FROM table_name ORDER BY id IS NULL, id ASC
    
    0 讨论(0)
  • 2020-11-22 17:20
    SELECT * FROM tablename WHERE visible=1 ORDER BY CASE WHEN `position` = 0 THEN 'a' END , position ASC
    
    0 讨论(0)
  • 2020-11-22 17:22

    You can coalesce your NULLs in the ORDER BY statement:

    select * from tablename
    where <conditions>
    order by
        coalesce(position, 0) ASC, 
        id DESC
    

    If you want the NULLs to sort on the bottom, try coalesce(position, 100000). (Make the second number bigger than all of the other position's in the db.)

    0 讨论(0)
  • 2020-11-22 17:26

    Something like

    SELECT * FROM tablename where visible=1 ORDER BY COALESCE(position, 999999999) ASC, id DESC
    

    Replace 999999999 with what ever the max value for the field is

    0 讨论(0)
  • 2020-11-22 17:32

    I found this to be a good solution for the most part:

    SELECT * FROM table ORDER BY ISNULL(field), field ASC;
    
    0 讨论(0)
  • 2020-11-22 17:33

    MySQL has an undocumented syntax to sort nulls last. Place a minus sign (-) before the column name and switch the ASC to DESC:

    SELECT * FROM tablename WHERE visible=1 ORDER BY -position DESC, id DESC
    

    It is essentially the inverse of position DESC placing the NULL values last but otherwise the same as position ASC.

    A good reference is here http://troels.arvin.dk/db/rdbms#select-order_by

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