通过 SQLAlchemy 获取随机行 [英] Getting random row through SQLAlchemy
本文介绍了通过 SQLAlchemy 获取随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 SQLAlchemy 从表中随机选择一个或多个行?
How do I select one or more random rows from a table using SQLAlchemy?
推荐答案
这在很大程度上是一个特定于数据库的问题.
This is very much a database-specific issue.
我知道 PostgreSQL、SQLite、MySQL 和 Oracle 具有按随机函数排序的能力,因此您可以在 SQLAlchemy 中使用它:
I know that PostgreSQL, SQLite, MySQL, and Oracle have the ability to order by a random function, so you can use this in SQLAlchemy:
from sqlalchemy.sql.expression import func, select
select.order_by(func.random()) # for PostgreSQL, SQLite
select.order_by(func.rand()) # for MySQL
select.order_by('dbms_random.value') # For Oracle
接下来,您需要通过您需要的记录数来限制查询(例如使用.limit()
).
Next, you need to limit the query by the number of records you need (for example using .limit()
).
请记住,至少在 PostgreSQL 中,选择随机记录有严重的性能问题;这里关于它的好文章.
Bear in mind that at least in PostgreSQL, selecting random record has severe perfomance issues; here is good article about it.
这篇关于通过 SQLAlchemy 获取随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文