查询表相关文章:mysql的ORDER_BY问题
select * from articles where article_id in(98,97,96,99)
返回的结果排序像
record 96 ...
record 97 ...
record 98 ...
record 99 ...
但我更喜欢的结果排序相同, '在(98,97,96,99)'。任何技巧,使其成为可能? 谢谢。
查询表相关文章:mysql的ORDER_BY问题
select * from articles where article_id in(98,97,96,99)
返回的结果排序像
record 96 ...
record 97 ...
record 98 ...
record 99 ...
但我更喜欢的结果排序相同, '在(98,97,96,99)'。任何技巧,使其成为可能? 谢谢。
中功能受到在列表的大小有限制。更有可能的是,一旦列表达到几百条,你的表现就会下降 - 你也可以单独检索记录并在客户端排序。
话虽如此,还有另一个MySQL函数,FIND_IN_SET你可能会考虑实现你的ORDER BY。但FIND_IN_SET最多只能处理64个成员。
ORDER BY
FIND_IN_SET(article_id, '98,97,96,99')
我想这可能工作:
select * from articles where article_id in(98,97,96) order by article_id desc
union
select * from articles where article_id = 99
我看不到你的订货任何图案,所以我想不出任何其他方式来做到这一点。
这看起来不可扩展到我,因为article_id序列的顺序可能是随机的,因为您说没有模式。 – Shawn 2009-11-06 04:40:57
96,97,98,99看起来像一个模式给我! – 2009-11-06 04:46:23
@Shawn:如果您希望它具有可伸缩性,您可以动态构建查询字符串: $ query =“select * from article whereid(”。$ in_list_1。“)order by article_id”。$ order1。“ union select * from article where article_id in(。“$ in_list_2”。)order by article_id“。$ order2 – FrustratedWithFormsDesigner 2009-11-06 04:49:54
您也许能够做这样的事情:
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;
不可扩展。如果我有500个ID,则查询可能会变胖。 – Shawn 2009-11-06 04:57:05
你能否多说一点'问题域'?每个查询的IN列表是否不同?无论ORDER BY方面如何,使用IN列表拉回数百行都不会缩小那么远。 – 2009-11-06 07:04:35