在SQL中,我可以使用IN
运算符和子查询,如下所示:
SELECT * FROM t1
WHERE (t1.some_int, t1.some_string) IN (
SELECT id, name FROM t2
)
但我无法将其转换为SQLAlchemy查询。据我所知,in_
方法仅适用于一列。有没有办法在SQLAlchemy中复制这个功能?
答案 0 :(得分:1)
您可以使用JOIN而不是子查询。像这样:
1
在sqlalchemy中:
T1:
SELECT * FROM t1 INNER JOIN t2 ON t1.some_int = t2.id AND t1.some_string = t2.name
T2:
class T1(DeclarativeBase):
__tablename__ = 't1'
__table_args__ = {'mysql_engine': 'InnoDB'}
id = Column(u'id', Integer, primary_key=True)
some_int = Column('some_int', Integer)
some_str = Column('some_str', String(45))
def __init__ (self, some_int, some_str):
self.some_int = some_int
self.some_str = some_str
源代码:
class T2(DeclarativeBase):
__tablename__ = 't2'
__table_args__ = {'mysql_engine': 'InnoDB'}
id = Column(u'id', Integer, primary_key=True)
name = Column('name', String(45))
data = Column('data', String(45))
def __init__ (self, name, data):
self.name = name
self.data = data
在结果引擎中生成sql:
data = session.query(T1).join(T2, and_(T1.some_int == T2.id, T1.some_string == T2.name)).all()