MySQL sort order by array value

后端 未结 2 1429
青春惊慌失措
青春惊慌失措 2020-12-08 04:41

I need to run a MySQL query where the order is determined by an array value.

My array is variable but the values in the array correspond to a field in my DB table ca

相关标签:
2条回答
  • 2020-12-08 05:05

    You want to get a list of items with the ids 5, 2, 1, 3 and output them in the same order. However, just running a select query will return the items in the order 1, 2, 3, 5.

    To order the results correctly you need to build a list of ORDER BY items describing the weights of the ids. This will look like

    ORDER BY id = 5 DESC, id = 2 DESC, id = 1 DESC, id = 3 DESC
    
    0 讨论(0)
  • 2020-12-08 05:09
    ORDER BY field(id, 9, 1, 4);
    

    http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_field

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