Pregunta

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?

¿Fue útil?

Solución

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

Otros consejos

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).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top