我在 SQLAlchemy Core 中加入 3 个表并按如下方式选择所有列:
rows = self.db.execute(self.execs.join(
self.orders.join(self.instruments)
).select(whereClause)).reduce_columns())
它运行良好,但如果我想选择列的子集:
reqdCols = [order.c.id, exec.c.last_modified, instruments.type]
rows = self.db.execute(self.execs.join(
self.orders.join(self.instruments)
).select(reqdCols, whereClause)).reduce_columns())
它不起作用并给出以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/apps/qtdist/pkgs/pub/cpython/python-2.7.6/lib/python2.7/site-packages/sqlalchemy/sql/selectable.py", line 807, in select
return Select(collist, whereclause, from_obj=[self], **kwargs)
File "/apps/qtdist/pkgs/pub/cpython/python-2.7.6/lib/python2.7/site-packages/sqlalchemy/sql/selectable.py", line 2219, in __init__
whereclause).self_group(against=operators._asbool)
File "/apps/qtdist/pkgs/pub/cpython/python-2.7.6/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 3438, in _literal_as_text
"SQL expression object or string expected."
sqlalchemy.exc.ArgumentError: SQL expression object or string expected.
替代方法是使用 select 而不是 Join.select 并使其与 where 子句隐式连接:
joinConditions = (orders.c.colx == execs.colx) & (execs.c.coly == instruments.c.coly)
select(reqdCols).where(and_(whereClause, joinConditions)
但出于性能原因,我更喜欢显式连接而不是隐式连接。有什么方法可以使用显式连接来选择列的子集吗?
最佳答案
可以按如下方式进行:
j = join(table1, table2) #optional third argument is join on part like table1.c.c1 == table2.c.c1
r = db.execute(select([table1.c.x, table2.c.y]).select_from(j)
关于python - 从 SQLAlchemy Core 中的多个表连接中选择列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25656935/