0

我正在尝试构建一个使用 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 的 1 个随机问题
  • 来自 IdTopic 4 的 1 个随机问题

共 6 行

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

谢谢大家 :)

4

1 回答 1

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
);
于 2015-02-19T15:39:47.743 回答