MySQL specify arbitrary order by id

前端 未结 3 1993
一向
一向 2020-12-17 18:49

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 (         


        
相关标签:
3条回答
  • 2020-12-17 18:49

    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.

    0 讨论(0)
  • 2020-12-17 19:13

    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
    
    0 讨论(0)
  • 2020-12-17 19:14

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

    0 讨论(0)
提交回复
热议问题