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

我正在使用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子句以上.

相关文章

Python中的函数(二) 在上一篇文章中提到了Python中函数的定...
Python中的字符串 可能大多数人在学习C语言的时候,最先接触...
Python 面向对象编程(一) 虽然Python是解释性语言,但是它...
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定...
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非...
在windows下如何快速搭建web.py开发框架 用Python进行web开发...