[英]SQLalchemy how do I query from another table based on the dates from another table?
So I'm trying to query the number of access attempts, failed and success, on a daily basis.因此,我尝试每天查询访问尝试的次数、失败次数和成功次数。 These are the tables I have created.
这些是我创建的表。
class SystemLog(Base):
__tablename__ = 'SystemLog'
ID = Column(Integer, primary_key=True)
Date = Column(Text)
Time = Column(Text)
PID = Column(Integer)
Message = Column(Text)
class Messages(Base):
__tablename__ = 'Messages'
ID = Column(Integer, primary_key=True)
Message = Column(Text)
AccessType = Column(Text)
IP = Column(Integer)
What I've tried:我试过的:
test = session.query(SystemLog.Date, Messages.AccessType, func.count(Messages.AccessType))\
.join(Messages).filter(SystemLog.ID==Messages.ID)\
.group_by(SystemLog.Date, Messages.AccessType).all()
How a SystemLog row looks like: SystemLog 行的外观如下:
How a Messages row looks like:消息行的外观如下:
But this gives me an error saying i need to use an ON clause.但这给了我一个错误,说我需要使用 ON 子句。 There are a few things I am unsure about as well.
我也不确定一些事情。 Are my tables created correctly and how do I do a join?
我的表是否正确创建?如何进行连接?
That being said, I cannot put all the columns into 1 table.话虽如此,我不能将所有列都放入 1 个表中。 At the very least, AccessType and IP has to be on a separate table and Date, Time, PID and Message have to be in 1 table.
至少,AccessType 和 IP 必须在一个单独的表中,并且日期、时间、PID 和消息必须在一个表中。
Based on the information in the comments:根据评论中的信息:
message
column in related rows is identical (implying each message is unique)message
列的内容是相同的(暗示每条消息都是唯一的) the query would look like this:查询将如下所示:
test = session.query(SystemLog.Date, Messages.AccessType, func.count(Messages.AccessType))\
.join(Messages, SystemLog.message == Messages.message)\
.group_by(SystemLog.Date, Messages.AccessType).all()
As far as the tables are concerned, I'd try to use more specific data types, for example Date
should be a sqlalchemy.Date
or sqlachemy.DateTime
.就表格而言,我会尝试使用更具体的数据类型,例如
Date
应该是sqlalchemy.Date
或sqlachemy.DateTime
。 And joining on a long string like message
could be slow, ideally you'd join on an integer value.加入像
message
这样的长字符串可能会很慢,理想情况下你会加入 integer 值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.