Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

python 3.x - Selecting a random row from postgresql database is returning "None"

I am using Python 3, psycopg2 and trying to retrieve a single random row from my database if the scanned_status = 'false' but it is returning 'None'. My connection to the database is fine. Could somebody please help me with the sql. I have 3 columns: network_number, scanned_status, number_of_scans.

Here is my sql statement

def random_network_number():
    """ Retrieve a random network number from the database """
    sql_statement = "SELECT * FROM ip_store WHERE (scanned_status = false) 
    OFFSET floor(random() * (SELECT COUNT(*) FROM ip_store)) LIMIT 1;"
    network_number = execute_sql_statement(sql_statement)
    output_information(network_number)
    return network_number

Output

[ * ] None

Process finished with exit code 0
question from:https://stackoverflow.com/questions/66067107/selecting-a-random-row-from-postgresql-database-is-returning-none

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A simpler version of your SQL would be:

SELECT * FROM ip_store WHERE (scanned_status = false) ORDER BY random() LIMIT 1;

I have a similar use case that has alway returned a record using the ORDER BY random() method.

I believe the problem with your original SQL is that you are using the count of ALL records to calculate your OFFSET and then applying it to a filtered query. I bet your OFFSET is greater than the number of filtered rows. The ORDER BY random() eliminates that problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...