哟个random效率太低了
时间: 2023-10-01 14:11:29 浏览: 72
确实,使用 `order_by(func.random())` 随机获取数据的效率比较低,因为它会对所有的数据进行排序,如果数据量很大,那么排序的开销就非常大。
有一种更高效的方式是使用 `func.random()` 和 `offset()` 函数结合使用,先随机生成一个偏移量,再获取偏移量之后的十条数据。示例代码如下:
```python
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from your_module import YourModel
# 创建数据库连接
engine = create_engine('postgresql://user:password@localhost:5432/your_database')
Session = sessionmaker(bind=engine)
session = Session()
# 获取数据总数
total = session.query(YourModel).count()
# 随机获取十条数据
offset = func.floor(func.random() * total).cast('integer')
query = session.query(YourModel).offset(offset).limit(10)
result = query.all()
```
其中,`YourModel` 是你的模型类,`your_module` 是包含模型类的模块名。`func.random()` 表示随机生成一个浮点数,`total` 表示数据总数,`func.floor()` 表示向下取整,`cast('integer')` 表示强制转换为整型。`offset` 表示偏移量,`query = session.query(YourModel).offset(offset).limit(10)` 表示获取偏移量之后的十条数据。这种方式不需要对所有数据进行排序,效率比较高。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)