pythonsqlalchemy组合来自两个表的查询

2024-06-26 00:28:14 发布

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

我有两个表没有这样的关系:

hurst = Table('Hurst', metadata,
    Column('symbol_id' , Integer, primary_key=True), 
    Column('Date'      , String(20), nullable=False),
    Column('symbol'    , String(40), nullable=False),
    Column('HurstExp'  , Float,      nullable=False),
)

fundamental = Table('Fundamental', metadata,
    Column('symbol_id' , Integer,    primary_key=True), 
    Column('Date'      , String(20), nullable=False),
    Column('symbol'    , String(40), nullable=False),
    Column('MarketCap' , Float,      nullable=False),
)

下面的每个查询都可以正常工作。我如何将它们结合起来,这样我才能得到价值超过50000000000的赫斯特公司?在

^{pr2}$

如果尝试使用联接,则会出现错误:

j = join(hurst, funda, hurst.c.symbol == funda.c.symbol)
stmt = select([hurst]).select_from(j)
theJoin = run(stmt)


Traceback (most recent call last):
  File "/home/idf/anaconda3/lib/python3.5/site-packages/sqlalchemy/engine/base.py", line 1139, in _execute_context
    context)
  File "/home/idf/anaconda3/lib/python3.5/site-packages/sqlalchemy/engine/default.py", line 450, in do_execute
    cursor.execute(statement, parameters)

   cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: Fundamental

我甚至不能做简单的版本

# This will return more results than you are probably expecting.
s = select([hurst, funda])
run(s)

Tags: keyidfalseexecutestringtablecolumninteger
2条回答

我不相信你能连接两个数据库。在

一个表在一个数据库中,另一个在另一个数据库中:

dbh = create_engine('sqlite:///hurst.db')
dbf = create_engine('sqlite:///fundamental.db')

您应该将所有表放在同一个database.db文件中,并有一个db = create_engine('sqlite:///database.db')。在

更正:你可以这样做:Cross database join in sqlalchemy

但是您真的希望每个表都在一个单独的数据库中吗?在

目前还没有一个环境来测试这一点,但是应该可以使用以下方法:

j = join(husrt, funda, (hurst.c.symbol_id == funda.c.symbol_id) & (funda.c.MarketCap > 50000000000))
stmt = select([hurst]).select_from(j)
run(stmt)

this SQL Alchemy docs page.签出sqlalchemy.sql.expression.join

相关问题 更多 >