问题
Question title might be a bit vague, so feel free to change it into something that makes more sense, I just couldn't find the right words.
So here is my problem:
In my table there are 2 important columns
- date_added (a datetime value)
- special_price (numeric)
special_price is either NULL
or a numeric value depending on what the special price is.
I'll describe the way I want to order my result now:
First I want to see all the items with no special_price (NULL
) ordered by date (newest first), Then I want to see the items that do have a special_price (so anything other than NULL
) ordered by date.
At first I tried this:
SELECT * FROM products ORDER BY special_price, date_added DESC
This worked great for the first part where all the special_price values where NULL
, but when it started with the the items that did have a special_price ordered on the value that was in the special_price column. This makes sense of course because in the query I wanted to order by special_price first.
So how can I let the query ignore the value of special_price and just see whether it's NULL
or not? So I get all NULL
's ordered by date and then I get all the NOT NULL
's ordered by date.
回答1:
ORDER BY IF( ISNULL( special_price ), 0, 1 ), date_added DESC
回答2:
I'd use
SELECT *, IF(special_price IS NULL, 0, 1) AS orderer FROM products ORDER BY orderer, date_added DESC
that works fine for what you want to accomplish
来源:https://stackoverflow.com/questions/6857110/how-can-i-sort-by-multiple-columns-but-not-by-value