使用Python从表中选择一个随机行 [英] Select a random row from the table using Python

查看:177
本文介绍了使用Python从表中选择一个随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的表。我使用MySQL进行数据库查询。

Below is the my table.I use MySQL for the database queries.

表的结构

我想通过从表格中取出问题来随机打印问题。

I want to print questions randomly by taking the questions from the table. How can I do that using Python?

推荐答案

from random import randint
num = randint(1,5)

然后执行数据库查询:

SELECT question FROM your_table WHERE ques_id = num;

或者:

SELECT question FROM your_table LIMIT num-1, 1;

num是1到5之间的随机数,替换 num 在查询中,它仅返回1行。请注意,它是从索引0开始的,因此第一个参数应为 num-1 ,而不是第二个参数 num 始终为1,因为每个查询只希望获得一行。

num would be a random number between 1 and 5, replace num in the query and it only returns 1 row. Be aware it is starting from index 0, therefore the first argument should be num-1 other than num, second argument is always 1 because you only want to get one row per query.

这篇关于使用Python从表中选择一个随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆