MySQL for specific values ​​and then DESC?

Say I have a mySQL table in which there is a field called "name"

This field contains one name for each row.

There are 10 lines:

Apple
Pear
Banana
Orange
Grapefruit
Pineapple
Peach
Apricot
Grape
Melon

How would I form the request, so I choose from the table, I want the details to be displayed as follows:

Peach
Apple
Apricot
... and then everything else is listed by descending order.

So basically I want to show several of the indicated results at the top of the list, and then the rest of the results in descending order.

Thank.

+5
source share
3 answers

You can do something like this:

select *
from fruit
order by
    case name
        when 'Peach'   then 1
        when 'Apple'   then 2
        when 'Apricot' then 3
        else 4
    end,
    name

This should work in any SQL database.

+6
source

IF(). IF() :

IF(expr1,expr2,expr3)

expr1 TRUE (expr1 < > 0 expr1 < > NULL), IF() expr2; expr3. IF() , , .

, :

SELECT *
FROM fruit
ORDER BY
    IF(name = 'Peach', 0, 1),
    IF(name = 'Apple', 0, 1),
    IF(name = 'Apricot', 0, 1),
    name DESC

, . , name='Peach', 0, 1. ASC, 0 1, , "" . , . "" "1". "Apple" , . Etc... DESC.

, CASE() IF() s:

CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END

, value = compare_value. , . , ELSE NULL, ELSE-.

+1

Since you are using php, you can read your answers in an array, the pop elements you want at the top can be stored in a temporary array. Sort the source array in alphabetical order, and then add a temporary array.

-1
source

All Articles