我有一个包含问题的表格,我想从每个类别中随机选择 25 个问题。
表“问题”如下所示:
类别为:C PC P PP
id 问题类别 答案1 答案2 答案3
最佳答案
最简单的方法是使用 union all
以及每个类别的子查询:
(select * from questions where category = 'C' order by rand() limit 25)
union all
(select * from questions where category = 'PC' order by rand() limit 25)
union all
(select * from questions where category = 'P' order by rand() limit 25)
union all
(select * from questions where category = 'PP' order by rand() limit 25)
如果您有很多类别或很多问题(数十万或更多),那么您可能需要一个性能更好的查询。但对于较少量的数据,这可能没问题。
我想强调的是,对于此类查询,union all
比 union
更好。 union
删除重复项,添加在这种情况下不需要的附加处理。
关于php - 我有 4 个类别,如何从表中每个类别 25 个问题中随机选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23540643/