0

my query is:

select * from table where id IN (1,5,4,3,2)

what I want is exactly same as this order not from 1...5 but 1,5,4,3,2. How can I do that?

Machavity
  • 30,841
  • 27
  • 92
  • 100
kodfire
  • 1,612
  • 3
  • 18
  • 57

1 Answers1

1

MYSQL's FIELD function and ORDER BY can help out here.

SELECT 
 *
FROM 
 [table]
WHERE 
 id IN (1,5,4,3,2)
ORDER BY 
 FIELD(id, 1,5,4,3,2)

negatieve FIELD(id, 1,5,4,3,2) can't make use of the index on id column.

Or without the function FIELD

SELECT 
 *
FROM (

  SELECT 
   1 AS number
  UNION 
  SELECT 
   5 AS number
  UNION 
  SELECT 
   4 AS number
  UNION 
  SELECT 
   3 AS number
  UNION 
  SELECT 
   2 AS number
) 
 AS numbers
INNER JOIN 
 [table]
ON
 [table].id = numbers.number

positive can use a index on id column.
negative harder to understand because of the delivered table

Raymond Nijland
  • 11,488
  • 2
  • 22
  • 34