SQLAlchemy使用子查询保留外连接

时间:2014-10-31 08:41:34

标签: join python-3.x sqlalchemy

我一直试图弄清楚这个查询有什么问题,并且完全难倒了。

基本上,我有两个表,一个名为MainHeatMap的父表和一个名为MainHeatMapReportLog的子表(下面的结构)

class MainHeatMap(Base):
    __tablename__ = 'MainHeatMap'
    MapID = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
    Abbrev = Column(String(6), nullable=False, unique=True)  #ID for API
    Name = Column(String(20), unique=True, nullable=False)
    Visible = Column(Boolean(), default=True)
    Alert = Column(Boolean(), default=False)
    ManualCancelAlert = Column(Boolean(), default=False)
    Reports = relationship('MainHeatMapReportLog',
                           primaryjoin='MainHeatMap.MapID == MainHeatMapReportLog.MapID',
                           backref='Map', lazy='dynamic'
                           )

    def __init__(self, Name, Abbrev, ManualCancelAlert=False):
        self.Name = Name
        self.Abbrev = Abbrev
        self.ManualCancelAlert = ManualCancelAlert

class MainHeatMapReportLog(Base): 
    __tablename__ = 'MainHeatMapReportLog'
    LogID = Column(Integer, primary_key=True, nullable=False)
    MapID = Column(Integer, ForeignKey('MainHeatMap.MapID'), nullable=False)
    Status = Column(String(8), index=True)
    LogDate = Column(TIMESTAMP(), nullable=False, default=datetime.utcnow())
    ReportingApplication = Column(String(15), nullable=False)
    Message = Column(String(255))

    def __init__(self, Status, ReportingApplication, Message):
        self.Status = Status
        self.ReportingApplication = ReportingApplication
        self.Message = Message

我正在尝试创建一个查询,该查询为我提供MainHeatMap表中'Visible'设置为True的每条记录,以及MainHeatMapReportLog表中每个记录的最新子记录(如果有)。

此查询的SQL将是:

SELECT A.MapID, A.Abbrev, A.Name, A.Visible, A.Alert, A.ManualCancelAlert, B.ReportDate
FROM MainHeatMap A
LEFT JOIN (
            SELECT MapID, Max(LogDate) as ReportDate
            FROM MainHeatMapReportLog
            GROUP BY MapID
            ) B
ON A.MapID = B.MapID
WHERE A.Visible = 1

然而,当我尝试运行以下行时,我收到错误

  

'Alias'对象没有属性'MapID'

LatestReportDate = Session.query(models.MainHeatMapReportLog.MapID,
                             func.max(models.MainHeatMapReportLog.LogDate).label('ReportDate')
                             ).group_by(models.MainHeatMapReportLog.MapID).subquery()

LatestReports = Session.query(models.MainHeatMap).outerjoin(
    (LatestReportDate, (models.MainHeatMap.MapID==LatestReportDate.MapID))
).filter(models.MainHeatMap.Visible==True).all()

子查询如果更改为.all()方法似乎工作正常,所以它必须是我尝试将表和子查询连接在一起的方式。我的google-fu暗示Alias用于自连接,但我不明白这种情况下的引用,我是否正在调用models.MainHeatMap错误?

如果有人能指出我正确的方向,我们将不胜感激。

0 个答案:

没有答案