[英]python sqlalchemy combine query from two tables
我有兩個不相關的表:
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),
)
以下每個查詢都可以正常工作。 如何將它們結合起來,所以我可以得到只有那些價值超過500億以上公司的赫斯特?
# -*- 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)
目前沒有環境可以對此進行測試,但是應該采取以下措施:
j = join(husrt, funda, (hurst.c.symbol_id == funda.c.symbol_id) & (funda.c.MarketCap > 50000000000))
stmt = select([hurst]).select_from(j)
run(stmt)
在這個SQL Alchemy文檔頁面上查看sqlalchemy.sql.expression.join
。
我不相信你可以加入兩個數據庫 。
您的一個表位於一個數據庫中,另一個位於另一個數據庫中:
dbh = create_engine('sqlite:///hurst.db')
dbf = create_engine('sqlite:///fundamental.db')
您應該將所有表放在同一個database.db
文件中,並使用一個db = create_engine('sqlite:///database.db')
。
更正:您可以這樣做: 在sqlalchemy中交叉數據庫加入
但是你真的想將每個表放在一個單獨的數據庫中嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.