简体   繁体   中英

mysql order_by question

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.

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.

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

您可能可以执行以下操作:

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;

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' )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM