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

标签 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)

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

最佳答案

可以按如下方式进行:

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/

相关文章:

python - 打包C/Python项目时使用distutils的原因

python - 在 Python 中测试电子邮件实现

sql - 如何在SQLAlchemy或SqlSoup ORM中自动反射(reflect)表关系?

python - 如何抑制 sqlalchemy.engine.base.Engine 记录到标准输出?

python - 组合两个 numpy 数组并将它们转换为数据帧

python - TensorFlow 中的矩阵幂

python - Python中概率密度函数的更快卷积

python - SQLAlchemy 引用表名 - 无法重新定义 'quote' 或 'quote_schema' 参数

python - SqlAlchemy 将方括号放在 sql server 2014 表名上

python - sqlalchemy.exc.OperationalError : (pymysql. err.OperationalError)(2013, 'Lost connection to MySQL server during query')