Question

How do I avoid a filesort when I want to order a query by condition in MySQL?

ORDER BY (videos_count > 0) DESC, name

Would it be better to cache a has_videos boolean column as well as the count?

Était-ce utile?

La solution

How about partitioning the query into two, first the ones with at least one video, then (only if needed) the rest:

select *  from video_table  
where video_count > 0
order by name

And if you need to go beyond those:

select *  from video_table  
where video_count = 0
order by name

Autres conseils

In a general sense, in order to avoid a filesort you generally need to hit an index - and in order to hit an index, you generally need to be sorting on bare column values (since indices are created for columns, generally).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top