MySQL specify arbitrary order by id

被刻印的时光 ゝ 提交于 2019-12-18 04:42:33

问题


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.


回答1:


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.




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/4327159/mysql-specify-arbitrary-order-by-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!