问题
I have got a MySql query that orders me results by no
column (int, can be null).
Simple example:
SELECT * FROM table ORDER BY no ASC
I would like to get a resultset sorted like
1, 2, 3, 10, 52, 66, NULL, NULL, NULL
but I get
NULL, NULL, NULL, 1, 2, 3, 10, 52, 66
Is it possible with SQL query ?
回答1:
Could you try this?
ORDER BY ISNULL(no),no;
回答2:
You can use a CASE
statement to tweak ordering:
SELECT *
FROM table
ORDER BY case when no is null then 2 else 1 end, no
This orders on "nullableness" first, and no
second.
回答3:
SELECT * FROM table ORDER BY ISNULL(field), field ASC;
回答4:
SELECT * FROM table ORDER BY COALESCE(no,999999) ASC
Just replace the 999999 with something larger if your numbers are naturally bigger than that.
回答5:
Ok, I think I got it:
SELECT * FROM table WHERE no IS NOT NULL ORDER BY no ASC
UNION
SELECT * FROM table WHERE no IS NULL
Or is there any better way ?
回答6:
SELECT * FROM table ORDER BY no ASC NULLS LAST
来源:https://stackoverflow.com/questions/1880278/sql-order-by-no-with-nulls-at-the-end