如何从表中选择 2 个不同的随机行? [英] How can I select 2 different random rows from a table?

查看:29
本文介绍了如何从表中选择 2 个不同的随机行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有

row=session.query(Item).order_by(func.random()).limit(2)
name1=row[0].name
name2=row[1].name

这给了我每个条目的第一列(名称).问题是,我得到了多个(它会选择相同的随机行两次.我希望它总是不同的.有没有办法在没有 if, then 语句的情况下做到这一点?

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 ?

为什么会说 limit ?我已经设置了限制(2)

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

推荐答案

似乎在 func.random() 上使用 order_by 在 SQL 中是个坏主意 (http://www.webtrenches.com/post.cfm/avoid-rand-in-mysql).相反,我计算了表的长度,找到了这个长度的 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 :)

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 个不同的随机行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆