Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query return values in a set sequence

Tags:

sql

I have been trying for a while now to return data from the database with the ID(int) values in the following order.

3, 6, 1, 9, 2, 5.

Is there anyway this can be done?

EDIT: Ok i made a bit of a stuff up in my post. the ID's above are just an example.

I am trying to do this dynamically, based around how many records from another table are linked to the record i want to pull out, e.g. i host 3 branches and each branch has a group of shops how would i determine which has the most?

I hope this helps.

like image 969
Reaper Avatar asked Jul 13 '26 22:07

Reaper


2 Answers

Yes, something like this:

select ID from tablename
order by
  CASE WHEN ID = 3 THEN 1
       WHEN ID = 6 THEN 2
       WHEN ID = 1 THEN 3
       WHEN ID = 9 THEN 4
       WHEN ID = 2 THEN 5
       WHEN ID = 5 THEN 6
       ELSE 7 END, ID ASC

This will put 3,6,1,9,2,5 and afterwords the other numbers in ascending order.

like image 194
aF. Avatar answered Jul 15 '26 14:07

aF.


select cols from table where
order by 
   case ID when 3 then 0 
   when 6 then 1 
   when 1 then 2
   when 9 then 3 
   ...
   end

You get the idea...

like image 29
Icarus Avatar answered Jul 15 '26 15:07

Icarus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!