MySQL - SELECT ... WHERE id IN (..) - 正确的顺序

发布于 2024-10-19 05:15:44 字数 208 浏览 0 评论 0原文

我有以下查询

SELECT * FROM table WHERE id IN (5,4,3,1,6)

,我想按照 id in.. 中指定的顺序检索元素,这意味着它应该返回:

5 ....
4 ....
3 ....
1 ....
6 ....

关于如何执行此操作的任何想法?

I have the following query

SELECT * FROM table WHERE id IN (5,4,3,1,6)

and I want to retrieve the elements in the order specified in the id in.., meaning it should return:

5 ....
4 ....
3 ....
1 ....
6 ....

Any ideas on how to do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

情愿 2024-10-26 05:15:44

使用 FIELD()

SELECT * FROM table WHERE id IN (5,4,3,1,6) ORDER BY FIELD(id, 5,4,3,1,6);

Use FIELD():

SELECT * FROM table WHERE id IN (5,4,3,1,6) ORDER BY FIELD(id, 5,4,3,1,6);
我的鱼塘能养鲲 2024-10-26 05:15:44
SELECT * FROM table WHERE id IN (5,4,3,1,6) ORDER BY FIELD (id, 5,4,3,1,6)
SELECT * FROM table WHERE id IN (5,4,3,1,6) ORDER BY FIELD (id, 5,4,3,1,6)
梅倚清风 2024-10-26 05:15:44

如果有人仍在搜索,我刚刚找到了它。

SELECT * FROM `table` WHERE `id` IN (4, 3, 1) ORDER BY FIELD(`id`, 4, 3, 1)

您可以找到该函数的参考此处

In case anyone is still searching I just found it..

SELECT * FROM `table` WHERE `id` IN (4, 3, 1) ORDER BY FIELD(`id`, 4, 3, 1)

And a reference for the function you can find HERE

你げ笑在眉眼 2024-10-26 05:15:44

那么你必须为每个 id 创建一个 Id,所以:

id |顶部

1 = 5
2 = 4
3 = 3
4 = 1
6 = 6

使用 IN 语句仅查看这些值是否在列表中,而不以任何特定顺序对它们进行排序

Well your going to have to create a Id for each of the id's so:

id | otherid

1 = 5
2 = 4
3 = 3
4 = 1
6 = 6

using the IN STATEMENT only looks to see if those values are in the List, doesnt order them in any specific order

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文