How can I select 2 different random rows from a table?

懵懂的女人 提交于 2019-12-13 16:44:02

问题


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, I get multiples (it will select the same random row twice. I want it to always be different. Is there a way to do this without an if, then statement?

if its useful, when I print row, it gives me something like this:

SELECT items.id AS items_id, items.name AS items_name, items.data AS items_data FROM items ORDER BY random() LIMIT ? OFFSET ?

why would it say limit ? I have put in limit(2)


回答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()



回答2:


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

Check the below link for reference.

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



来源:https://stackoverflow.com/questions/19507467/how-can-i-select-2-different-random-rows-from-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!