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

Sqlalchemy 1.4+ 如何通过Table对象实现单列查询 无需导入select

解决方案

你可以通过Table对象自带的with_only_columns()方法指定要查询的列,完全不需要额外导入select函数,符合你的需求:

单字段查询示例(仅查login列)

# 构造查询语句
get_user_login_st = users.select()\
    .with_only_columns(users.c.login)\
    .where(users.c.login == user.phone_number)

# 异步会话执行需要加await
result = await connection.execute(statement=get_user_login_st)
# 直接获取单个返回值
login_value = result.scalar_one_or_none()

多字段查询示例(同时查login、phone_number两列)

get_user_part_st = users.select()\
    .with_only_columns(users.c.login, users.c.phone_number)\
    .where(users.c.login == user.phone_number)

result = await connection.execute(get_user_part_st)
row = result.fetchone()
# 取值可以用属性或者索引
# login = row.login
# phone = row.phone_number

错误写法原因说明

  1. users.select(users.c.login)写法错误:Table.select()方法本身不接收列作为入参,传入的参数会被误识别为筛选条件,因此还是会返回全表字段
  2. users.c.login.select()写法错误:Column对象本身没有实现select方法,因此会抛出属性不存在的异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 16:45:04