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

使用SQL/SQLAlchemy筛选指定列:律所案件数据查询问询

没问题,我来帮你搞定这个指定律所的数据筛选需求。先把你的原始数据整理成清晰的Markdown表格方便查看:

case_idlaw_firm_idparty_type
2001300896918Plaintiff
20013008961927Plaintiff
20013008961934Plaintiff
200130089691653Defendant
2001300896245649Plaintiff
20013008961534016Defendant
2001311137918Defendant
200131113750823Plaintiff
2001311137257164Defendant
20013111378055087Defendant

1. 纯SQL实现

要筛选指定律所ID的相关数据,直接用WHERE子句过滤law_firm_id字段就可以。比如咱们要找ID为918的律所所有案件记录,SQL语句如下:

SELECT case_id, law_firm_id, party_type
FROM *your_table_name*  -- 记得替换成你的实际表名
WHERE law_firm_id = 918;

如果是在程序里使用,为了避免SQL注入,建议用参数化查询。不同数据库的占位符略有区别,举几个常见例子:

  • PostgreSQL:用%s作为占位符
  • MySQL:用?作为占位符
  • SQL Server:用@param作为命名参数

参数化查询的SQL写法(以PostgreSQL为例):

SELECT case_id, law_firm_id, party_type
FROM *your_table_name*
WHERE law_firm_id = %s;

执行后会精准返回目标律所的关联案件:

case_idlaw_firm_idparty_type
2001300896918Plaintiff
2001311137918Defendant

2. SQLAlchemy实现

SQLAlchemy有Core(核心SQL表达式)和ORM(对象关系映射)两种常用用法,我都给你写出来:

2.1 SQLAlchemy Core 方式

先假设你已经初始化了数据库连接并定义了表结构:

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

# 初始化数据库连接和元数据
engine = create_engine('*your_database_connection_string*')  # 替换成你的数据库连接串
metadata = MetaData()

# 定义表结构(如果表已存在,也可以用metadata.reflect()自动加载)
case_parties = Table(
    '*your_table_name*', metadata,
    Column('case_id', Integer),
    Column('law_firm_id', Integer),
    Column('party_type', String)
)

# 构建并执行查询
target_law_firm_id = 918
query = case_parties.select().where(case_parties.c.law_firm_id == target_law_firm_id)

with engine.connect() as conn:
    result = conn.execute(query)
    # 遍历结果,可转换成字典方便处理
    for row in result:
        print(row._asdict())

2.2 SQLAlchemy ORM 方式

如果用ORM模型来操作,先定义对应的模型类:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker, declarative_base

Base = declarative_base()

# 定义模型类,映射数据库表
class CaseParty(Base):
    __tablename__ = '*your_table_name*'
    case_id = Column(Integer, primary_key=True)  # 根据实际主键规则调整
    law_firm_id = Column(Integer)
    party_type = Column(String)

# 初始化会话
engine = create_engine('*your_database_connection_string*')
Session = sessionmaker(bind=engine)
session = Session()

# 查询指定律所的数据
target_law_firm_id = 918
results = session.query(CaseParty).filter(CaseParty.law_firm_id == target_law_firm_id).all()

# 处理查询结果
for item in results:
    print(f"案件ID: {item.case_id}, 律所ID: {item.law_firm_id}, 当事人类型: {item.party_type}")

session.close()

根据你的实际开发场景选合适的方法就行,两种方式都能精准筛选出指定律所的所有关联案件数据~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:28:24