Skip to content Skip to sidebar Skip to footer

How Can I Select 2 Different Random Rows From A Table?

right now I have row=session.query(Item).order_by(func.random()).limit(2) name1=row[0].name name2=row[1].name Which gives me the first column(name) of each entry. The problem is,

Solution 1:

It seems that using order_by on func.random() is a bad idea in SQL (http://www.webtrenches.com/post.cfm/avoid-rand-in-mysql). Instead, I counted the length of the table, found 2 random numbers with in this length, and then queried the table to find the rows associated with these random numbers. Apparently this is faster. At least it doesn't have any repeats :)

number=session.query(func.count(Item.id)).scalar()
randoms=random.sample(range(number),2)
item1=session.query(Item).filter_by(id=randoms[0]+1).one()
item2=session.query(Item).filter_by(id=randoms[1]+1).one()

Solution 2:

SELECT items.id AS items_id, items.name AS items_name, items.data AS items_data
FROM items
ORDERBY random()
LIMIT 2;

Check the below link for reference.

http://www.tutorialspoint.com/sqlite/sqlite_limit_clause.htm

Post a Comment for "How Can I Select 2 Different Random Rows From A Table?"