MySQL 用 WHERE `id` IN (...) 指定确切的顺序
有没有一种简单的方法可以通过 WHERE id
IN (...) 子句分别对 MySQL 结果进行排序? 示例:
SELECT * FROM articles WHERE articles.id IN (4, 2, 5, 9, 3)
返回
Article with id = 4
Article with id = 2
Article with id = 5
Article with id = 9
Article with id = 3
也
SELECT * FROM articles WHERE articles.id IN (4, 2, 5, 9, 3) LIMIT 2,2
返回
Article with id = 5
Article with id = 9
更新:更具体地说,我想避免篡改 WHEREarticles.id IN (4, 2, 5, 9, 3)
中括号中的数据,因为这些 ID 是动态的并且会自动排序。
Is there an easy way to order MySQL results respectively by WHERE id
IN (...) clause?
Example:
SELECT * FROM articles WHERE articles.id IN (4, 2, 5, 9, 3)
to return
Article with id = 4
Article with id = 2
Article with id = 5
Article with id = 9
Article with id = 3
and also
SELECT * FROM articles WHERE articles.id IN (4, 2, 5, 9, 3) LIMIT 2,2
to return
Article with id = 5
Article with id = 9
Update: to be more specific, I want to avoid tampering with the data in parentheses in WHERE articles.id IN (4, 2, 5, 9, 3)
, since those IDs are dynamic and automatically ordered.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,有点像:
但这是非标准 SQL,而且有点味道。
Yeah, kind of:
but this is non-standard SQL and smells a bit.
这对我有用:
按字段排序(Product.id, 4,9,8,5,3,11,24,16)
This works for me:
ORDER BY FIELD(Product.id, 4,9,8,5,3,11,24,16)
MySQL 只使用 ORDER BY 进行排序。这就是为什么数据库表具有序数列之类的东西并不少见。
MySQL only sorts with ORDER BY. This is why it's not terribly uncommon for database tables to have something like an ordinality column.
我认为你做不到。不存在“明确”的排序; “in”语句只是告诉您要检索什么,并且没有有关排序的信息。
由于您给出的示例没有明显的顺序,因此最好的选择是在返回结果后在代码中处理此问题。
I don't think you can do that. There's no "explicit" ordering going on; the "in" statement simply tells you what to retrieve, and has no information about ordering.
Since the examples you've given have no obvious order, your best bet is to handle this in code after the result is returned.