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,then语句的情况下做到这一点?
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)
为什么会说限制?我已经限制(2)
2 个解决方案
#1
2
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 :)
似乎在func.random()中使用order_by在SQL中是一个坏主意(http://www.webtrenches.com/post.cfm/avoid-rand-in-mysql)。相反,我计算了表的长度,找到了这个长度的2个随机数,然后查询表以找到与这些随机数相关联的行。显然这更快。至少它没有任何重复:)
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
1
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
#1
2
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 :)
似乎在func.random()中使用order_by在SQL中是一个坏主意(http://www.webtrenches.com/post.cfm/avoid-rand-in-mysql)。相反,我计算了表的长度,找到了这个长度的2个随机数,然后查询表以找到与这些随机数相关联的行。显然这更快。至少它没有任何重复:)
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
1
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