加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 在SQLAlchemy中,如何查询复合主键?

发布时间:2020-12-16 22:48:54 所属栏目:Python 来源:网络整理
导读:我正在使用SQLAlchemy以编程方式查询具有复合外键的表.例如.: CREATE TABLE example (id INT NOT NULL,date TIMESTAMP NOT NULL,data VARCHAR(128)PRIMARY KEY (id,date)) 我想拿一个值列表并获取行例如: interesting_data = ( (1,'2016-5-1'),(1,'2016-6-

我正在使用SQLAlchemy以编程方式查询具有复合外键的表.例如.:

CREATE TABLE example (
id INT NOT NULL,date TIMESTAMP NOT NULL,data VARCHAR(128)
PRIMARY KEY (id,date)
)

我想拿一个值列表并获取行例如:

interesting_data = (
    (1,'2016-5-1'),(1,'2016-6-1'),(2,(3,)
select(
    [example.c.id,example.c.date,example.c.data],).where(example.primary_key.in_(interesting_data)

如果每列都是独立的,我可以做到

interesting_ids = [1,2,3]
interesting_dates = ['2016-5-1','2016-6-1']
select(
    [example.c.id,).where(
    example.c.id.in_(interesting_ids)
).where(
    example.c.date.in_(interesting_dates)
)

但这显然无法仅带来唯一匹配(id,date)元组.我怀疑有一种方法可以指定要查询的复合主键,但搜索后找不到任何文档.

最佳答案
在where子句中使用list comprehension:

from sqlalchemy import and_,or_,select

stmt = select(
    [example.c.id,example.c.data]
).where(or_(and_(example.c.id==data[0],example.c.date==data[1])
            for data in interesting_data))

但是,我注意到的另一个问题是您将日期列与字符串数据类型进行比较. interesting_data列表应该是

import datetime as dt

interesting_data = (
    (1,dt.date(2016,5,1)),6,)

另请注意,可以创建基本语句,然后逐步向其添加子句,从而导致(希望)更好的易读性和代码重用.

因此,可以将上面的内容写成

base_stmt = select([example.c.id,example.c.data])
wheres = or_(and_(example.c.id==data[0],example.c.date==data[1])
             for data in interesting_data))
stmt = base_stmt.where(wheres)

这会生成以下sql(由我添加的新行和空格):

SELECT example.id,example.date,example.data 
FROM example 
WHERE 
   example.id = :id_1 AND example.date = :date_1 
OR example.id = :id_2 AND example.date = :date_2
OR example.id = :id_3 AND example.date = :date_3 
OR example.id = :id_4 AND example.date = :date_4 
OR example.id = :id_5 AND example.date = :date_5

注意:如果要像这样过滤很多行,那么创建临时表,从interesting_data向此临时表插入行,然后将内部连接插入此表可能更有效,而不是如图所示添加where子句以上.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读