2015-12-19 60 views
3

合併查詢我有兩個不相關類似這樣的表格:蟒蛇SQLAlchemy的兩個表中的

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公司的hurst?

# -*- 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

請參閱編輯的文章。桌子是分開的。也許我需要以某種方式將它們聯繫起來,但兩個表格是分開創建的。 – Ivan

+0

您需要使用'sqlalchemy'的'backref'功能並使用外鍵或關係創建另一個表的引用。 – Abhinav

回答

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.jointhis SQL Alchemy docs page.

+0

請參閱編輯的文章。即使這個簡單的東西似乎沒有工作。 – Ivan

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

但你真的希望有每個表在一個單獨的數據庫?