You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用SQLAlchemy如何从数据库表中提取指定单列的全部值

解决方案

要只获取user_id列而非全量行数据,可通过with_entities()指定查询字段实现,两种常用写法如下:


写法1(兼容所有SQLAlchemy版本)

# 指定仅查询user_id字段,按id倒序排列
user_id_tuples = Draw.query.with_entities(Draw.user_id).order_by(desc('id')).all()
# 转换为纯user_id值的数组
user_id_array = [item[0] for item in user_id_tuples]

with_entities()会限制查询返回的字段,此时返回的结果是(user_id,)格式的元组列表,遍历取第一个元素即可得到纯值数组。


写法2(SQLAlchemy 1.4+ 简化写法)

使用scalars()方法可直接提取字段值,无需手动遍历元组:

user_id_array = Draw.query.with_entities(Draw.user_id).order_by(desc('id')).scalars().all()

补充说明

如果你需要的是id从小到大的正序排列(即表中从上到下的原生顺序),将desc('id')替换为Draw.id即可。

内容的提问来源于stack exchange,提问作者acc4232111

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 23:15:04