How to get RANDOM records from each category in MySQL?

前端 未结 3 1099
轮回少年
轮回少年 2020-12-11 18:23

In my MySQL database, I have a table with different questions in different categories.

I would like to write a SQL statement that returns 3 RANDOM questions of EACH

3条回答
  •  忘掉有多难
    2020-12-11 18:34

    In addition to the other answer, this is also another way to do it.

    SELECT r.* FROM random r
    WHERE (
      SELECT COUNT(*) FROM random r1
      WHERE r.category = r1.category AND r.id < r1.id
    ) <= 2
    ORDER BY r.category ASC, RAND()
    

提交回复
热议问题