2012-03-04 118 views
0

我想要获得10 rand结果,其中image !=''uid组和uid和这些uidselect uid from user_table where type='1'相同。但我的查询只返回2结果。哪里有问题?mysql group by uid其中与uid匹配的另一个查询

select * from article_table where image!='' 
order by rand() 
group by uid 
in (select uid from user_table where type='1') 
limit 10 

回答

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 

做,或你可能想从您user_table限制uid的数目,以使其更快地首先:

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 

我假设这里有很多文章给每个用户。虽然它看起来更可怕,但内部select中的order by rand()超过了一个较小的数据集,这会加快速度,外部select中的order by只能处理较少数量的行。

要小心,按照随机值排序可能会导致显着的性能下降,因为您必须遍历与where子句匹配的整个表。有alternatives

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