mysql从组中取N随机

时间:2015-02-19 15:34:59

标签: mysql sql analytical

我试图构建一个使用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);

结果必须是:

  • 来自IdTopic 1的2个随机问题
  • 来自IdTopic 2的2个随机问题
  • 来自IdTopic 3的随机问题
  • 来自IdTopic 4的随机问题

总共6行

使用OVER函数,我会按照RANDOM的IdTopic排序对数据进行分区,然后按rownumber< = 1或< = 2 ..

进行过滤

感谢大家:)

1 个答案:

答案 0 :(得分:1)

在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
);