tags:

views:

59

answers:

5

Query table articles:

select * from articles where article_id in(98,97,96,99)

returned result ordered like

record 96 ...
record 97 ...
record 98 ...
record 99 ...

but I prefer the result ordered the same as 'in(98,97,96,99)'. Any tricks to make it possible? Thanks.

+1  A: 

I suppose this might work:

select * from articles where article_id in(98,97,96) order by article_id desc
union
select * from articles where article_id = 99

I can't see any pattern to your ordering so I can't think of any other way to do this.

FrustratedWithFormsDesigner
This looks not scalable to me, coz the article_id sequence's order could be random as you said no pattern.
Shawn
96,97,98,99 looks like a pattern to me!
James Anderson
@Shawn: If you want it scalable, you could build the query string dynamically:$query="select * from articles where article_id in(".$in_list_1.") order by article_id ".$order1."unionselect * from articles where article_id in (."$in_list_2".) order by article_id ".$order2
FrustratedWithFormsDesigner
@FrustratedWithFormsDesigner: You way should work but looks too dirty tho. Thanks anyway.
Shawn
+1  A: 

Shawn, When you use IN Statement, in MYSQL

It compares the First record ID to your given ID. Then compares Second record ID to your given ID. So ...

So the result will be displayed in asc order.

If you need dont use IN statement. I would prefer to Retrieve Each record in loop.

Thankyou

RSK
Yes thought about that but still not scalable, I can have hundreds of id's in the 'in' statement, don't think putting query into a loop is a good idea. Thanks tho.
Shawn
Definitely that will make the process quite slow. But IN Statement not supports that you have mention
RSK
+1  A: 

You might be able to do something like this:

select * from articles where article_id in(98,97,96,99) order by article_id == 98 desc, article_id == 97 desc, article_id == 96 desc, article_id == 99 desc;
Chris AtLee
Not scalable. If I got 500 id's the query may grow fat.
Shawn
A: 

You'll have to do the sorting through code as it appears that the string 98,97,96,99 is also generated via code. Anyway, see if this helps:

SELECT * FROM
(
SELECT 1 AS SortKey, articles.* FROM articles WHERE article_id = 98
UNION
SELECT 2 AS SortKey, articles.* FROM articles WHERE article_id = 97
UNION
SELECT 3 AS SortKey, articles.* FROM articles WHERE article_id = 96
UNION
SELECT 4 AS SortKey, articles.* FROM articles WHERE article_id = 99
.
.
.
) AS ASDF
ORDER BY SortKey
Salman A
+1  A: 

The IN function is subject to a limit on the size of the list. More likely, once the list gets to a few hundred entries, your performance will drop off - you may as well retrieve the records individually and sort them in the client.

Having said that, there's another MySQL function, FIND_IN_SET you might consider to implement your ORDER BY. FIND_IN_SET can only handle up to 64 members in the set though.

ORDER BY
    FIND_IN_SET( article_id, '98,97,96,99' )
martin clayton