使用SQL/SQLAlchemy筛选指定列:律所案件数据查询问询
没问题,我来帮你搞定这个指定律所的数据筛选需求。先把你的原始数据整理成清晰的Markdown表格方便查看:
| case_id | law_firm_id | party_type |
|---|---|---|
| 2001300896 | 918 | Plaintiff |
| 2001300896 | 1927 | Plaintiff |
| 2001300896 | 1934 | Plaintiff |
| 2001300896 | 91653 | Defendant |
| 2001300896 | 245649 | Plaintiff |
| 2001300896 | 1534016 | Defendant |
| 2001311137 | 918 | Defendant |
| 2001311137 | 50823 | Plaintiff |
| 2001311137 | 257164 | Defendant |
| 2001311137 | 8055087 | Defendant |
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_id | law_firm_id | party_type |
|---|---|---|
| 2001300896 | 918 | Plaintiff |
| 2001311137 | 918 | Defendant |
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
相关产品推荐
相关产品推荐

