MySQL按类别限制每个类别的N.

时间:2015-01-03 06:35:45

标签: php mysql

id       title        category

1        hello1          1
2        hello2          2
3        hello3          1

查询

select  *
from    videos
where   category in
        (
        select  category
        from    videos
        group by 
               category
        having 
               count(*) < 3
ORDER BY RAND()
        )

我的目标是以随机顺序从每个类别中获取2个标题 我也想以这种方式获取记录

category1
title1
title2

category2
title1
title2

2 个答案:

答案 0 :(得分:1)

以下查询从每个类别中提供不超过两个随机行:

SELECT title, category
FROM (
  SELECT v.*,
     if( category = @last_cat,
         if( @last_cat:=category, @x:=@x+1,@x:=@x+1),
         if( @last_cat:=category, @x:=0,@x:=0)
     ) x
  FROM (SELECT @last_cat:=-9876, @x:=-91234) x,
       (SELECT * FROM videos ORDER BY category, rand()) v
) x
WHERE x < 2

演示:http://sqlfiddle.com/#!2/59cf9/8

答案 1 :(得分:0)

<强>已更新

请尝试此更新后的查询( SQL小提琴 - http://sqlfiddle.com/#!2/de35bb/9 ):

select  videos.*
from    videos
where   
    (
        select  COUNT(vid.id)
        from    videos AS vid
        WHERE videos.category = vid.category
    ) <= 2
ORDER BY
  videos.category, RAND()

我已经设法在SO上找到了解决方案: 的 Using LIMIT within GROUP BY to get N results per group? 其答案指向文章 的 How to select the first/least/max row per group in SQL 作者描述了执行此类任务的一些技巧。 以上查询是基于第二篇文章中提供的示例构建的,但还有其他形式可以解决此问题。