OOO
OOO

Reputation: 962

Selecting columns from mulitple table join in SQLAlchemy Core

I am joining 3 table in SQLAlchemy Core and selecting all columns as follows:

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

It works well but if I want to select a subset of 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())

It doesn't works and gives following error:

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.

Alternative would be to use select instead of Join.select and make it implicit join with where clauses:

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

But I would prefer explicit join over implicit for performance reasons. Is there any way to select subset of columns using explicit joins?

Upvotes: 3

Views: 3489

Answers (1)

OOO
OOO

Reputation: 962

It can be done as follows:

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)

Upvotes: 6

Related Questions