Preserving Ordering With WHERE in() Clause in MySQL
Today I ran into the code that pulls from database list of elements with
1
SELECT*FROMtableWHEREidIN(2,5,3,16,22,56,48)
where order of ids is important to be preserved after results found. When using SELECT this way you will get the results for every id but ordered by id in ascending order. I was looking around and found neat solution to make MySQL work for you to preserve the order of returned results. With ORDER BY FIELD clause like here
12
SELECT*FROMtableWHEREidIN(1,5,2,13,4)
ORDERBYFIELD(id,1,5,2,13,4)
you can keep the initial ordering. What is the catch. This way id field can not be used as indexed. Therefore,
12
EXPLAINSELECT*FROMtable
WHEREidIN(1,5,2,13,4)ORDERBYFIELD(id,1,5,2,13,4)
would give you the information that it is using filesort for results ordering which is not so nice. In general, when you have ids as the array with the ordering you need, it probably needs less resources to reorganize them in memory instead of letting MySQL doing it with filesort.
No comments:
Post a Comment