select * from ( select A.*,@nohit:=if(hit<>1,@nohit+1,0),@cnt:=if(@nohit=1,1,@cnt+1) num from ( select * from table order by hit=1 desc, rand() ) A, (select @cnt:=0,@nohit:=0) B ) A order by num<=5 desc, rand()
Here, first all hit = 1 are put at the beginning and all entries are sorted in random order. Further, in this set, hit = 1 and hit <> 1 are numbered consecutively, separately, starting with 1. That is, hit = 1 entries with numbers 1,2,3, ... and exactly hit <<1 1,2,3, ... We sort this set again, this time there are entries with numbers less than 5 at the beginning (there are 10 of them, 5 hits each and not hit ones), and then everything else.
order by hit=1 desc, rand()This is if you don’t need to select only 5 out of more than 5 hit - Mike