SQLAlchemy连接两个表

时间:2018-06-20 14:17:44

标签: python sqlalchemy

标题太糟糕了,对此我感到抱歉,但我想不出能描述情况的任何东西。

我有两个表,如下所示:

  

读数表具有一个外键,该外键连接到气象站读数

的ID

气象站的读数

-------------------------------------
| Id1 | StationId1 | Location | Time |
| Id2 | StationId2 | Location | Time |
|      ...                           |
--------------------------------------

读物

-----------------------------
| Id   | Foreign | Readings  |
| RId1 | Id1     | Reading 1 |
| RId2 | Id1     | Reading 2 |
| RId3 | Id1     | Reading 3 |
| RId4 | Id2     | Reading 4 |
| RId5 | Id2     | Reading 5 |
| RId6 | Id1     | Reading 6 |
|      ...                   |
------------------------------

每个电台都是已知的。有数百个。每次收集读数时,气象站的读数表中只有一个条目,而读数表中则有多个条目。我想做的是获取给定阅读ID的特定站条目的读数。

例如,我有 RId2 。我需要获取下表:

------------------------------------------------------------------
| Id1 | StationId1 | Location | Time | RId1 | Id1     | Reading 1 |
| Id1 | StationId1 | Location | Time | RId2 | Id1     | Reading 2 |
| Id1 | StationId1 | Location | Time | RId3 | Id1     | Reading 3 |
-------------------------------------------------------------------

注意:以下代码有点像伪代码。我不使用此代码,也不存在该表。我无权分享,因此必须这样做。

class StationReadings(Base):
    __tablename__ = 'StationReadings'
    Id = Column(Integer, primary_key=True)
    StationId = Column(Integer) # This normally has a foreign key too
    Location = Column(String)
    Time = Column(DateTime)
    Readings = relationship("Readings")


class Readings(Base):
    __tablename__ = 'Readings'
    Id = Column(Integer, primary_key=True)
    Station = Column(Integer, ForeignKey('StationReadings.Id'))
    Readings = Column(Float)

我相信这样的东西也可以用来增强它:

primaryjoin="and_(StationReadings.Id==Readings.Station)"

0 个答案:

没有答案