質問

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