php - 我有 4 个类别,如何从表中每个类别 25 个问题中随机选择?

标签 php mysql

我有一个包含问题的表格,我想从每个类别中随机选择 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 allunion 更好。 union 删除重复项,添加在这种情况下不需要的附加处理。

关于php - 我有 4 个类别,如何从表中每个类别 25 个问题中随机选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23540643/

相关文章:

php - mysqli_fetch_array() 还是 mysqli_fetch_all()?

php - 当变量为空时使用 IN_ARRAY 获取错误

mysql - 为什么在我没有设置密码的情况下提示我输入 MySQL 服务器密码?

mysql - 当键自动递增时插入忽略?

php - paypal php响应或返回过程?

javascript - 动态评论功能代码

php - 重启 Docker 容器之谜

php - 获取 php 中表中数据的总出现次数

php - 使用 get 方法自定义 URL Helper 重定向

php - 将注释放在可创建语句的中间