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?

有帮助吗?

解决方案

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

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top