groupby和orderby rand()使用mysql

时间:2017-11-05 05:03:07

标签: mysql

table structure

questions_id    category_id
     1              1
     2              1
     3              2
     4              2
     5              3
     6              3

我的查询

SELECT * FROM questions GROUP BY category_id ORDER BY RAND() LIMIT 0, 3

它显示任何三个question_id的

SET @row_number = 0;
select (@row_number := @row_number+1) AS num, id, question_name, 
category_id FROM questions ORDER BY RAND()  LIMIT 8;

显示任意8个问题_id

另一个

SELECT * FROM questions a 
INNER JOIN (SELECT category_id FROM questions GROUP BY category_id) AS b
ON a.category_id = b.category_id
ORDER BY RAND() LIMIT 0, 3

它也显示相同,但​​我希望每个category_id都是相同的question_id ......

1 个答案:

答案 0 :(得分:0)

SELECT id, question_name, category_id FROM
(
    SELECT id, question_name, category_id, @rn := IF(@prev = category_id, 
    @rn + 1, 1) AS rn, @prev := category_id
    FROM questions JOIN (SELECT @prev := NULL, @rn := 0) AS vars ORDER BY  
    category_id
) AS T1
WHERE rn <= 2 ORDER BY RAND()