Select a random row from the table using Python

2019-09-18 19:48发布

问题:

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

Structure of the table

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

回答1:

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

Then db query:

SELECT question FROM your_table WHERE ques_id = num;

Alternatively:

SELECT question FROM your_table LIMIT num-1, 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.



回答2:

If all the Ids are in order, get the max one and use the random library to get a random number from 1 to the max id in database.

from random import randint

random_id = randint(1,my_max_id)

then use random_id to get the item from the database.

If you have not setup your python mysql connection, you can refer this How do I connect to a MySQL Database in Python?.