【问题标题】:mysql group by uid which uid match another querymysql group by uid 哪个 uid 匹配另一个查询
【发布时间】:2012-03-04 12:28:19
【问题描述】:

我想得到 10 兰特的结果,image !=''uid 分组,这些uidselect uid from user_table where type='1' 相同。但我的查询只返回 2 个结果。问题出在哪里?

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

【问题讨论】:

    标签: mysql group-by


    【解决方案1】:

    我会用 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_tableuids 的数量,以便更快地开始:

    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

    【讨论】:

      【解决方案2】:

      下面的查询会做到这一点,

      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 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-05
        • 1970-01-01
        • 1970-01-01
        • 2018-04-08
        • 2018-09-11
        • 1970-01-01
        相关资源
        最近更新 更多