Sherin Jose
Sherin Jose

Reputation: 2516

How to retrieve rows in the required order in mysql

I have a table as follows,

table1

enter image description here

When i m using the query

"SELECT cat_title FROM table1 WHERE cat_id IN(21,10,25,4)"

the result is in the order

cat_title

Bank

Beauty Parlour

Car

Accomodation

But i need the result as given in the query like,

cat_title

Car

Beaty Parlour

Accomodation

Bank

What will i do?

Upvotes: 1

Views: 67

Answers (2)

solaimuruganv
solaimuruganv

Reputation: 29847

 SELECT cat_title FROM table1 
 Where cat_id IN(21,10,25,4)
 ORDER BY (
            CASE WHEN cat_id = 21 THEN 0
          WHEN cat_id = 4 THEN 1
              WHEN cat_id = 10 THEN 2
          WHEN cat_id = 25 THEN 3
        END
           )

Upvotes: 1

Omesh
Omesh

Reputation: 29121

You can try this:

SELECT cat_title
FROM table1
WHERE cat_id IN(21,10,25,4)
ORDER BY (cat_id = 21) DESC, (cat_id = 10) DESC, (cat_id = 25) DESC, (cat_id = 4) DESC;

or

SELECT cat_title
FROM table1
WHERE cat_id IN(21,10,25,4)
ORDER BY FIND_IN_SET(cat_id, ('21,10,25,4'));

Upvotes: 2

Related Questions