Join SQLAlchemy与子查询的左外部联接
一段时间以来,我一直在试图找出这个问题的症结所在,我完全被难住了 基本上,我有两个表,一个名为MainHeatMap的父表和一个名为MainHeatMapReportLog结构的子表Join SQLAlchemy与子查询的左外部联接,join,python-3.x,sqlalchemy,Join,Python 3.x,Sqlalchemy,一段时间以来,我一直在试图找出这个问题的症结所在,我完全被难住了 基本上,我有两个表,一个名为MainHeatMap的父表和一个名为MainHeatMapReportLog结构的子表 class MainHeatMap(Base): __tablename__ = 'MainHeatMap' MapID = Column(Integer, primary_key=True, autoincrement=True, nullable=False) Abbrev = Colu
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的每条记录以及MainHeatMap ReportLog表中每个记录的最新子记录(如果有)
此查询的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”
如果将子查询更改为.all方法,则该子查询似乎可以正常工作,因此它必须是我尝试将表和子查询连接在一起的方式。我的google fu建议将别名用于自连接,但我不理解本例中的引用,我是否错误地调用了models.main热图
如果有人能为我指出正确的方向,我将不胜感激。请尝试连接条件中的models.MainHeatMap.MapID==LatestReportDate.c.MapID。另外,请查看最近非常类似的问题和答案[,您可以加载相关表MainHeatMapReportLog的整个实例,而不仅仅是字段。如果您有多个具有相同最新日志日期的MainHeatMapReportLog,它还可以解决重复结果问题。嗨,Van,非常感谢您的回答,我现在尝试一下,并查看您提供的链接。Anotherr问题,如果您不介意的话:我在查询中包含的“c”是做什么的?这是列的别名,请参阅文档。再次感谢,Van!:
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()