简体   繁体   中英

Select rows where a column matches an element of a list SQLAlchemy

I have two tables with the following columns:

con
---
id
code

pa
---
con_id (foreign key and references con.id)
data

I also have a list:

names = ['a', 'b', 'c']

I want to join the two tables to get a table/view with three columns:

pa.con_id
pa.data
con.code 

and return the rows where con.code is one of the elements in names . At the moment, I can join my tables and return all the columns:

engine = create_engine('postgresql://postgres:postgres@localhost/db')
metadata = MetaData(bind=engine)
pa = Table('pa', metadata, autoload=True)
contract = Table('contract', metadata, autoload=True)
res = pa.join(contract).select().execute()

but I don't know how to do a where which matches one of the items in my names list.

Use the in_ operator of Column to do column in (....) ; then use it in filter with your names list.

pa.join(contract).select().where(contract.c.code.in_(names)).execute()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM