简体   繁体   中英

mysql order by field with NULL values last

I have been having an issue when using the FIELD function in my order by clause.

My situation is a product can have three categories and the user can choose what category to show first. So there are three possible queries that can be formed. These are:

Query 1

SELECT 
    *
FROM
    my_table
WHERE
    main_categories_id = 2
ORDER BY FIELD(product_condition,
        'graded',
        'new',
        'used');

Query 2

SELECT 
    *
FROM
    my_table
WHERE
    main_categories_id = 2
ORDER BY FIELD(product_condition,
        'new',
        'graded',
        'used');

Query 3

SELECT 
    *
FROM
    my_table
WHERE
    main_categories_id = 2
ORDER BY FIELD(product_condition,
        'used',
        'new',
        'graded');

This does not work well when the product condition is NULL because it always shows the rows with a NULL value first. I need these to appear last.

I have tried adding NULL to the FIELD function but this doesnt seem to work.

Does anyone know a way I can achieve this?

Thanks for your help.

You can either:

  1. Explicitly sort first by whether the column is NULL and then by its value:

     ORDER BY product_condition IS NULL, FIELD(...) 

    This works because product_condition IS NULL will be 0 for non- NULL columns and 1 for NULL columns; and in the (default) ascending order, the former will obviously come first.

  2. Rely on the fact that NULL is sorted last in descending orderings and reverse the arguments to FIELD() :

     ORDER BY FIELD(product_condition, ...) DESC 

你应该使用'ORDER BY FIELD desc'来结束显示空值。

Try This...

SELECT * FROM my_table WHERE main_categories_id = 2 ORDER BY CASE WHEN  product_condition IS NULL THEN 1 ELSE 0 END,FIELD( product_condition, "graded", "new", "used" );

same for other two...

Null in the last. Actual Table

+------+---------+
| col1 | col2    |
+------+---------+
| 1    | Closed  |
| 2    | Open    |
| 3    | Pending |
| 4    | New     |
| 5    | NULL    |
| 6    | Closed  |
| 7    | New     |
| 8    | NULL    |
+------+---------+

select * from testing2 order by case when col2 IS NULL THEN 1 ELSE 0 END, FIELD(col2,'New','Open','Closed','Pending');


+------+---------+ | col1 | col2 | +------+---------+ | 4 | New | | 7 | New | | 2 | Open | | 1 | Closed | | 6 | Closed | | 3 | Pending | | 5 | NULL | | 8 | NULL | +------+---------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM