从SQLAlchemy Core中的多个表连接中选择列

时间:2014-09-04 03:41:23

标签: python sqlalchemy

我正在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)

但出于性能原因,我更倾向于使用隐式连接。有没有办法使用显式连接选择列的子集?

1 个答案:

答案 0 :(得分:4)

可以按照以下方式完成:

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)