Skip to content
Advertisement

MySQL SELECT in order of array values

Can anyone help me with a Query query?

I have an array of IDs $IDvalues = array("128", "159", "7", "81", "82", "83");

And need to retrieve data from another table in the order of the array. At the moment, I have this query:

JavaScript

But it’s getting it in numerical order (7, 81, 82, 83, 128, 159). I need 128 first, then 159… Is there anything I can use in the query to retain the order?

Thanks all!

Advertisement

Answer

Without another column in the table from which to sort in an ORDER BY, you cannot get a determinate sort order back from the SQL query. It is possible to concoct an ORDER BY using an elaborate chain like

JavaScript

But that is a terrible idea.

Instead, I would recommend storing the fetched rows in an array indexed by their id column, then using your original $IDvalues array to iterate it:

JavaScript

This method will not be efficient if the size of $IDvalues is many thousands because it requires fetching all rows before writing them out, but it seems like you are dealing with a smaller array.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement