2012-03-04 67 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