Selecting Random Rows in MySQL(在 MySQL 中选择随机行)
问题描述
我正在开发一个测验网站,我有一个存储所有问题的数据库.有不同类型的测验,如数学、科学、历史等.所有问题都存储在一个表格中.
I am developing a quiz website, and I have a database which stores all of the questions. There are different types of quizzes, like math, science, history, etc. All of the questions are stored in one table.
我的问题表如下所示:
questions ( qno(int) ,type(int), question, .... ,... )
qno 是主键,type 用于跟踪测验类型.:
qno is the primary key, and type is used to keep track of the quiz type.:
if type = 1 (math)
type = 2(science)
现在,我想为每种类型的测试随机选择一些问题.例如,我可能只想为数学测试选择一些随机的 20 个问题.
Now, I want to select some random questions for each type of test. For example, I may want to select some random 20 questions for only the math test.
MySQL 有办法选择随机行吗?
Does MySQL have some way to select random rows?
推荐答案
您可以使用 rand 函数在 MySQL 中对行进行排序,然后使用 limit 取前 10 个(或您想要的任何数量).
You can use the rand function in MySQL to order the rows, and then take the top 10 (or however many you want) with limit.
select * from table order by rand() limit 10
如果你只想要数学题:
select * from table where type = 1 order by rand() limit 10
这篇关于在 MySQL 中选择随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 MySQL 中选择随机行
基础教程推荐
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 无法解决整理冲突 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
