我希望获得10个兰特结果,image !=''
,uid
分组,uid
select uid from user_table where type='1'
来自select * from article_table where image!=''
order by rand()
group by uid
in (select uid from user_table where type='1')
limit 10
。但我的查询只返回2结果。问题出在哪里?
{{1}}
答案 0 :(得分:2)
我使用join
代替
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
或者您可能希望限制uid
中user_table
的数量,以便更快开始:
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
我在这里假设每个用户都有很多文章。虽然它看起来更可怕,但内部选择中的order by rand()
覆盖了较小的数据集,这会加快速度,而外部选择中的order by
只需要处理较少的行数。
请注意,按随机值排序可能会导致严重的性能损失,因为您必须遍历与where子句匹配的整个表。有alternatives。
答案 1 :(得分:1)
以下查询将执行此操作,
SELECT *
FROM article_table
WHERE image!=''
AND uid IN (SELECT DISTINCT uid
FROM user_table
WHERE TYPE = '1'
LIMIT 10)
GROUP BY uid
ORDER BY Rand()
LIMIT 10