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

如何在SQLAlchemy中按Question字段过滤并获取关联ID

过滤Question列并获取关联ID的实现方案

方法一:使用SQLAlchemy Core查询

直接通过SQLAlchemy的Core API执行过滤查询,获取匹配问题的ID:

from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, select

# 初始化引擎和表对象(复用你的代码)
engine = create_engine('sqlite:///question_database', echo=True)
meta = MetaData()
question_database = Table(
    "question_database", meta,
    Column("ID", Integer, primary_key=True),
    Column("Question", String),
    Column("Answer", String),
)

# 定义过滤条件,比如匹配包含特定关键词的问题
filter_condition = question_database.c.Question.like("%某个关键词%")
# 或者精确匹配:question_database.c.Question == "具体问题内容"

# 构建查询,只选择ID列
query = select(question_database.c.ID).where(filter_condition)

# 执行查询并获取结果
with engine.connect() as conn:
    result = conn.execute(query)
    # 提取所有匹配的ID
    matched_ids = [row[0] for row in result.fetchall()]
    print(matched_ids)

方法二:直接执行原生SQL语句

如果更习惯原生SQL,也可以直接执行查询:

from sqlalchemy import create_engine

engine = create_engine('sqlite:///question_database', echo=True)

with engine.connect() as conn:
    # 模糊查询示例,替换为你的过滤条件
    sql = "SELECT ID FROM question_database WHERE Question LIKE ?"
    result = conn.execute(sql, ("%某个关键词%",))
    matched_ids = [row[0] for row in result.fetchall()]
    print(matched_ids)

说明

  • like("%关键词%") 用于模糊匹配,若需要精确匹配,直接使用==运算符或=即可
  • echo=True 会打印执行的SQL语句,方便调试,生产环境可关闭

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:45:44