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,753
  • 72
  • 57
  • 129
sureyn
  • 117
  • 6

4 Answers4

7
SELECT * FROM user ORDER BY IF(id=3 OR id=5, id, ~id) ASC
Neeraj
  • 8,625
  • 18
  • 60
  • 89
  • @a_horse_with_no_name: execute the query SELECT IF(id=3 OR id=5, id, ~id) FROM user and you will get the answer – Neeraj Jan 16 '13 at 12:33
  • It gives strange numbers. What are they? –  Jan 16 '13 at 12:36
  • they are temporary auto generate numbers regardless of taking care of number of records in a table. – Neeraj Jan 16 '13 at 12:36
  • 1
    It is very well similar to this `SELECT * FROM table1 ORDER BY IF(id=3 OR id=5, id, id-8) desc` But here you need to define the number to the max id ;) ; – bonCodigo Jan 16 '13 at 12:50
  • That's right. but we don't want to bother about the max id. :) – Neeraj Jan 16 '13 at 12:51
  • This worked better for me. SELECT * FROM `user` ORDER BY case when id = 3 then 0 when id = 5 then -1 else id end ASC – sureyn Feb 01 '13 at 11:29
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.

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,814
  • 5
  • 39
  • 60
  • Is there any other way without using UNION? – sureyn Jan 16 '13 at 12:31
  • By the SQL standard you are not able to order parts of a UNION. Does MySQL allow this nevertheless? And is the order retained even though MySQL will try to remove duplicates between the two parts? –  Jan 16 '13 at 12:31
  • My bad. I guess I made assumptions on the standard. – ApplePie Jan 16 '13 at 16:29
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
  • 258,903
  • 69
  • 498
  • 492
  • 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