简体   繁体   中英

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

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

UPDATED

Please try this updated query ( 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? 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. The above query was built upon an example provided in the second article, but there are other forms of solving this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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