简体   繁体   English

MySQL每个类别的类别限制N

[英]MySQL Group by category limit N from each category

TABLE

id       title        category

1        hello1          1
2        hello2          2
3        hello3          1

Query 询问

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

my goal is to get 2 titles from each category in a random order also I want to fetch records in this manner 我的目标是从每个类别中以随机顺序获得2个标题,我也想以此方式获取记录

category1
title1
title2

category2
title1
title2

The below query gives no more than two random rows from each category: 以下查询提供每个类别最多两个随机行:

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

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

UPDATED 更新

Please try this updated query ( SQL Fiddle - http://sqlfiddle.com/#!2/de35bb/9 ): 请尝试以下更新查询( SQL Fiddle - 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()

I've managed to find the solution on SO here: Using LIMIT within GROUP BY to get N results per group? 我设法在这里找到解决方案: 在GROUP BY中使用LIMIT以每个组获得N个结果? in which answer points to the article How to select the first/least/max row per group in SQL where author describes a few techniques of performing such task. 其中答案指向文章“ 如何在SQL选择每个组的第一/最小/最大行” ,作者描述了执行此任务的几种技术。 The above query was built upon an example provided in the second article, but there are other forms of solving this problem. 上面的查询基于第二篇文章中提供的示例,但是还有其他形式的解决此问题的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM