我有两张与此无关的表:
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),
)
以下每个查询都可以正常运行。我如何将它们结合起来,这样才能 那些价值超过50,000,000,000的公司?
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 13 19:22:35 2015
@author: idf
"""
from sqlalchemy import *
def run(stmt):
rs = stmt.execute()
return rs
# Let's re-use the same database as before
dbh = create_engine('sqlite:///hurst.db')
dbf = create_engine('sqlite:///fundamental.db')
dbh.echo = True # We want to see the SQL we're creating
dbf.echo = True # We want to see the SQL we're creating
metadatah = MetaData(dbh)
metadataf = MetaData(dbf)
# The users table already exists, so no need to redefine it. Just
# load it from the database using the "autoload" feature.
hurst = Table('Hurst', metadatah, autoload=True)
funda = Table('Fundamental', metadataf, autoload=True)
hurstQ = hurst.select(hurst.c.HurstExp < .5)
run(hurstQ)
fundaQ = funda.select(funda.c.MarketCap > 50000000000)
run(fundaQ)
如果我尝试使用联接,我会收到错误:
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)
答案 0 :(得分:0)
目前还没有一个环境可以对此进行测试,但有些内容应该有效:
j = join(husrt, funda, (hurst.c.symbol_id == funda.c.symbol_id) & (funda.c.MarketCap > 50000000000))
stmt = select([hurst]).select_from(j)
run(stmt)
上查看sqlalchemy.sql.expression.join
答案 1 :(得分:0)
我不相信你可以加入两个数据库。
您的一个表位于一个数据库中,另一个位于另一个数据库中:
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
但是你真的想把每个表放在一个单独的数据库中吗?