I'd do it with a join
instead
select *
from article_table at
join ( select uid
from user_table
where type = '1' ) ut
on at.uid = ut.uid
where image != ''
group by at.uid
order by rand()
limit 10
Or you may want to restrict the number of uid
s from your user_table
to make it quicker to begin with:
select at.*
from article_table at
join ( select uid
from user_table
where type = '1'
order by rand()
limit 10 ) ut
on at.uid = ut.uid
where image != ''
group by at.uid
order by rand()
limit 10
I'm assuming here that there are many articles to each user. Although it looks more horrible, the order by rand()
in the inner select is over a smaller dataset, which'll speed things up and the order by
in the outer select only has to deal with a smaller number of rows.
Be careful, ordering by a random value can incur a significant performance hit as you have to go through the entire table that matches your where clause. There are alternatives.