MySQL通过id指定任意顺序

发布于 2024-10-05 09:59:30 字数 187 浏览 2 评论 0原文

是否可以为 MySQL SELECT 语句指定任意顺序?例如,

SELECT * FROM table_name WHERE id IN (1, 3, 2, 9, 7) ORDER BY (1, 3, 2, 9, 7);

IN 后面直接列出的数字顺序似乎并不重要。

Is it possible to specify an arbitrary order for a MySQL SELECT statement? E.g.,

SELECT * FROM table_name WHERE id IN (1, 3, 2, 9, 7) ORDER BY (1, 3, 2, 9, 7);

The order of the numbers listed directly after IN do not seem to matter.

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

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

发布评论

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

评论(3

鸠魁 2024-10-12 09:59:30

FIND_IN_SET 函数可以解决问题

SELECT * FROM table_name WHERE id IN (1, 3, 2, 9, 7) ORDER BY FIND_IN_SET(id, '1,3,2,9,7');

http:// /dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set

编辑:请注意 find_in_set 函数的字符串参数中缺少空格。

FIND_IN_SET function will do the trick

SELECT * FROM table_name WHERE id IN (1, 3, 2, 9, 7) ORDER BY FIND_IN_SET(id, '1,3,2,9,7');

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set

EDIT: Note the lack of spaces in the string argument of the find_in_set function.

远山浅 2024-10-12 09:59:30

查看 mysql 的按字段排序。我认为它会完全满足你的要求。

Check out mysql's ORDER BY FIELD. I think it will do exactly what you want.

赠佳期 2024-10-12 09:59:30

简单答案:

使用另一个“ordering”int 字段来检测您的数据,然后按该字段进行 ORDER BY。这应该是大多数时候所需要的。我已经成功地做到了这一点,客户可以通过在订购字段中应用 -1 或 -99 等低值,将某些产品添加到特色列表等中。

复杂的答案:

如果您想要标准化该排序,并且如果您可能有另一个字段作为订单中的第二个因素(该字段已经在您的主表中),则这将适用。如果您有与每个订购点相关的其他信息(例如注释),这也会有所帮助。或者,如果很多表要实现这种任意顺序,并且您想从一个地方编排/修改该顺序。

您要做的是将“任意”订单放在可以加入的表中,然后按该字段排序:

SELECT t.*, o.ordering
FROM table_name AS t
LEFT JOIN table_name_ordering AS o ON t.ordering_id = o.id
ORDER BY o.ordering, t.other_field

Easy answer:

Instrument your data with another "ordering" int field and then ORDER BY that field. This should be all that's necessary most of the time. I've successfully done this where clients can bubble certain products up a featured list, etc. by applying low values like -1 or -99 into the ordering field.

Complex answer:

This would apply if you wanted to normalize that ordering, and if maybe you had another field as the second factor in the order, that's already in your main table. This would also help if you have other information associated with each ordering point, like a note. Or, if lots of tables are going to implement this arbitrary order, and you want to orchestrate/modify that ordering from one place.

What you'd do is place the "arbitrary" order in a table you can join and then ordering by that field:

SELECT t.*, o.ordering
FROM table_name AS t
LEFT JOIN table_name_ordering AS o ON t.ordering_id = o.id
ORDER BY o.ordering, t.other_field
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文