在SQLAlchemy C中从多表联接中选择列

2024-09-28 18:48:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在SQLAlchemy Core中加入3个表并选择所有列,如下所示:

rows = self.db.execute(self.execs.join(
                         self.orders.join(self.instruments)
                      ).select(whereClause)).reduce_columns())

如果我想选择一个子集,但我想选择一个列:

^{pr2}$

它不工作,并给出以下错误:

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而不是加入。选择并使其与where子句隐式连接:

joinConditions = (orders.c.colx == execs.colx) & (execs.c.coly == instruments.c.coly)
select(reqdCols).where(and_(whereClause, joinConditions)

但是出于性能原因,我更喜欢显式连接而不是隐式连接。有没有任何方法可以使用显式联接来选择列的子集?在


Tags: appsinselfsqlalchemylibpackageslinesite