mysql 从组中随机取N

mysql take N random from group

我正在尝试构建一个使用 OVER() 会很容易的查询,但是 mysql 没有这些分析功能...

我必须从 IdTopic 为 1 或 2 的小组中抽取 2 个随机问题,并从主题 3 和 4 中抽取 1 个随机问题。

 CREATE TABLE Questions (
  IdQuestion INT
  ,IdTopic TINYINT
  ,Question VARCHAR(50)
  ,Answer TINYINT
)

INSERT INTO Questions VALUES(1,1,'T1 Q1 A0',0);
INSERT INTO Questions VALUES(2,1,'T1 Q2 A1',1);
INSERT INTO Questions VALUES(3,1,'T1 Q3 A1',1);
INSERT INTO Questions VALUES(4,1,'T1 Q4 A0',0);
INSERT INTO Questions VALUES(5,1,'T1 Q5 A0',0);
INSERT INTO Questions VALUES(6,1,'T1 Q6 A1',1);
INSERT INTO Questions VALUES(7,1,'T1 Q7 A1',1);
INSERT INTO Questions VALUES(8,1,'T1 Q8 A0',0);

INSERT INTO Questions VALUES(9,2,'T2 Q9 A0',0);
INSERT INTO Questions VALUES(10,2,'T2 Q10 A0',0);
INSERT INTO Questions VALUES(11,2,'T2 Q11 A1',1);
INSERT INTO Questions VALUES(12,2,'T2 Q12 A1',1);
INSERT INTO Questions VALUES(13,2,'T2 Q13 A1',1);

INSERT INTO Questions VALUES(14,3,'T3 Q14 A0',0);
INSERT INTO Questions VALUES(15,3,'T3 Q15 A1',1);
INSERT INTO Questions VALUES(16,3,'T3 Q16 A1',1);
INSERT INTO Questions VALUES(17,3,'T3 Q17 A0',0);
INSERT INTO Questions VALUES(18,3,'T3 Q18 A1',1);

INSERT INTO Questions VALUES(19,4,'T3 Q19 A0',0);
INSERT INTO Questions VALUES(20,4,'T3 Q20 A0',0);
INSERT INTO Questions VALUES(21,4,'T3 Q21 A0',0);
INSERT INTO Questions VALUES(22,4,'T3 Q22 A0',0);
INSERT INTO Questions VALUES(23,4,'T3 Q23 A1',1);

结果必须是:

总共 6 行

使用 OVER 函数,我将按随机排序的 IdTopic 对数据进行分区,然后按行号 <= 1 或 <=2..

进行过滤

感谢大家:)

在 MySQL(或大多数数据库)中执行此操作的最简单方法可能就是使用 union all。除非你有很多问题(成千上万),否则性能应该没问题:

(select q.*
 from questions q
 where idTopic = 1
 order by rand()
 limit 2
) union all
(select q.*
 from questions q
 where idTopic = 2
 order by rand()
 limit 2
) union all
(select q.*
 from questions q
 where idTopic = 3
 order by rand()
 limit 1
) union all
(select q.*
 from questions q
 where idTopic = 4
 order by rand()
 limit 1
);