MySQL Orderby a number, Nulls last

前端 未结 12 2522
再見小時候
再見小時候 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:36

    For a DATE column you can use:


    NULLS last:

    ORDER BY IFNULL(`myDate`, '9999-12-31') ASC
    

    Blanks last:

    ORDER BY IF(`myDate` = '', '9999-12-31', `myDate`) ASC
    
    0 讨论(0)
  • 2020-11-22 17:40

    To achieve following result :

    1, 2, 3, 4, NULL, NULL, NULL.

    USE syntax, place -(minus sign) before field name and use inverse order_type(Like: If you want order by ASC order then use DESC or if you want DESC order then use ASC)

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

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

    Try using this query:

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

    Why don't you order by NULLS LAST?

    SELECT * 
    FROM tablename
    WHERE visible = 1 
    ORDER BY position ASC NULLS LAST, id DESC 
    
    0 讨论(0)
  • 2020-11-22 17:46

    You can swap out instances of NULL with a different value to sort them first (like 0 or -1) or last (a large number or a letter)...

    SELECT field1, IF(field2 IS NULL, 9999, field2) as ordered_field2
      FROM tablename
     WHERE visible = 1
     ORDER BY ordered_field2 ASC, id DESC
    
    0 讨论(0)
  • 2020-11-22 17:47

    This is working fine:

    SELECT * FROM tablename ORDER BY position = 0, position ASC;
    

    position
    1 
    2
    3
    0
    0
    
    0 讨论(0)
提交回复
热议问题