MySQL specify arbitrary order by id

前端 未结 3 2009
一向
一向 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 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
    

提交回复
热议问题