6

I have a user table that contain 8 records. I want to arrange the data in descending order on the basis of field id (that is a primary key of that table) but except id 3 and 5. So eventually the result should be like

id  name
--  ----
3   peter
5   david
8   john
7   stella
6   jim
4   jack
2   nancy
1   scott

Except id 3 and 5 rest of the data should be arranged in descending order and 3 and 5 should come in ascending order.

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
sureyn
  • 117
  • 6

4 Answers4

7
SELECT * FROM user ORDER BY IF(id=3 OR id=5, id, ~id) ASC
a_horse_with_no_name
  • 440,273
  • 77
  • 685
  • 758
neeraj
  • 7,235
  • 16
  • 55
  • 84
6

something like this:

order by 
   case 
     when id = 3 then 999
     when id = 5 then 998
     else id
   end desc

This assumes that you really don't have more than 8 rows. Otherwise you must change the "magic" numbers that move 3 and 5 to the top.

a_horse_with_no_name
  • 440,273
  • 77
  • 685
  • 758
1

I think the trick here is to use an enum.

SELECT id, name FROM my_table WHERE id IN (3, 5) ORDER BY ASC
UNION
SELECT id, name FROM my_table WHERE id NOT IN(3, 5) ORDER BY DESC
ApplePie
  • 8,247
  • 5
  • 35
  • 55
1

In MySQL, there is a function called FIELD which *returns zero if a value is not found on the list` eg,

SELECT *
FROM   tableName
ORDER BY FIELD(id, 5, 3) DESC, id DESC
John Woo
  • 238,432
  • 61
  • 456
  • 464
  • But that return the id like 3,5,1,2,4,6 and so on... Where as output should come like 3,5,8,7,6,4.... – neeraj Jan 16 '13 at 12:53