Sqlalchemy连接两个表

2024-10-02 22:25:11 发布

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

标题很糟糕,我很抱歉,但我想不出任何东西可以描述这种情况

我有两张表,如下所示:

Readings table has a foreign key which is connected to the ID of Weather stations' readings

气象站的读数

-------------------------------------
| 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)"

Tags: key代码idtimecolumnlocationinteger读数