MySQL Orderby a number, Nulls last

2019-01-01 01:32发布

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

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

The problem with this is that NULL entries for 'position' are treated as 0. Therefore all entries with position as NULL appear before those with 1,2,3,4. eg:

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

Is there a way to achieve the following ordering:

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

10条回答
路过你的时光
2楼-- · 2019-01-01 01:54

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

SELECT * FROM table ORDER BY ISNULL(field), field ASC;
查看更多
时光乱了年华
3楼-- · 2019-01-01 01:54

Why don't you order by NULLS LAST?

SELECT * 
FROM tablename
WHERE visible = 1 
ORDER BY position ASC NULLS LAST, id DESC 
查看更多
荒废的爱情
4楼-- · 2019-01-01 01:59

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
查看更多
余生请多指教
5楼-- · 2019-01-01 02:04

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

查看更多
倾城一夜雪
6楼-- · 2019-01-01 02:10

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
查看更多
浪荡孟婆
7楼-- · 2019-01-01 02:13
SELECT * FROM tablename WHERE visible=1 ORDER BY CASE WHEN `position` = 0 THEN 'a' END , position ASC
查看更多
登录 后发表回答