Forum Moderators: coopster

Message Too Old, No Replies

select rows from table in order of array

question about mysql.

         

ikbenhet1

8:32 pm on Dec 30, 2003 (gmt 0)

10+ Year Member



select * from table where number="1" or number="3" or number="5"

Is there a way to make this query behave like this:
first select where number = 1 then where number=3 then where number=5?

Right now it's obviously selecting the first one it finds in the table first.
Thanks.

jatar_k

8:36 pm on Dec 30, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



select * from table where number in (1,3,5) order by number asc

ikbenhet1

8:42 pm on Dec 30, 2003 (gmt 0)

10+ Year Member



Thank you jatar, but what if i want to select where number in (2,1,3) that is my actual problem.
Thank you.

jatar_k

8:46 pm on Dec 30, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



select * from table where number in (2,1,3) group by number

not sure, actually I think that will still order them but try it and see.

ikbenhet1

8:59 pm on Dec 30, 2003 (gmt 0)

10+ Year Member



no, this way it selects the first number it encounters in the table that is in the IN()-array first.

So how to keep the order? not specificly for IN().
the question could also apply to this query:

select from table where number=2 or number=1 or number=5

jatar_k

9:01 pm on Dec 30, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



did you try the group by instead of order by with the different result orders?

coopster

9:05 pm on Dec 30, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I agree, jatar_k. From the manual [mysql.com]:

If all values are constants, then all values are evaluated according to the type of
expr
and sorted. The search for the item is then done using a binary search. This means IN is very quick if the IN value list consists entirely of constants.

However, I think you can define the ORDER BY:

SELECT * FROM table WHERE number IN (2,1,3) ORDER BY number=2 DESC, number=1 DESC, number=3 DESC;

ikbenhet1

9:06 pm on Dec 30, 2003 (gmt 0)

10+ Year Member




yes, order by / group by , it keeps selecting the first one it finds first no matter what the order is in the IN() or where clause.

ikbenhet1

9:12 pm on Dec 30, 2003 (gmt 0)

10+ Year Member



wow, that works great. thanks! this forum is really great! Thanks to you both.