gpt4 book ai didi

mysql从组中随机抽取N个

转载 作者:行者123 更新时间:2023-11-29 12:24:03 24 4
gpt4 key购买 nike

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

总共 6 行

使用 OVER 函数,我将按 IdTopic 按 RANDOM 排序对数据进行分区,然后按行号 <= 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
);

关于mysql从组中随机抽取N个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28610351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com