在SQLAlchemy中对同一个表数据加入两个查询的正确方法是什么?
即我的数据类定义如下:
class DataMeasurement(Base):
__tablename__ = 'DataMeasurement'
id = Column(Integer, Sequence('data_measurement_id_seq'), primary_key=True)
data_source = Column(String)
timestamp = Column(DateTime)
sensor_output = Column(Float)
...我想加入以下两个有匹配时间戳的查询:
q1 = self.session.query(DataMeasurement).filter_by(data_source='Sensor1').order_by(DataMeasurement.timestamp)
q2 = self.session.query(DataMeasurement).filter_by(data_source='Sensor2').order_by(DataMeasurement.timestamp)
# ...and now what?
有没有办法简单地做到这一点? ...或者我是否以一种根本上有缺陷的方式解决这个问题(我对SQLAlchemy很新)?
答案 0 :(得分:6)
使用子查询:
subq = self.session.query(DataMeasurement).\
filter_by(data_source='Sensor1').subquery()
q = self.session.query(
DataMeasurement.timestamp,
# Use labels to distinguish between identically named columns.
# This is optional.
subq.c.sensor_output.label('output1'),
DataMeasurement.sensor_output.label('output2')
).filter(
(DataMeasurement.data_source == 'Sensor2') &
(DataMeasurement.timestamp == subq.c.timestamp)
)
# Simply get a list of named tuples.
print q.all()
# Or access each column using properties.
for row in q:
print row.timestamp, row.output1, row.output2
您还可以将结果作为DataMeasurement
个对象获取:
subq = self.session.query(DataMeasurement).\
filter_by(data_source='Sensor1').subquery()
# Use alias to associate mapped class to a subquery.
dmalias = aliased(DataMeasurement, subq)
q = self.session.query(dmalias, DataMeasurement).filter(
(DataMeasurement.data_source == 'Sensor2') &
(DataMeasurement.timestamp == dmalias.timestamp)
)
# For each row you get a tuple containing two DataMeasurement objects.
for dm1, dm2 in q:
print dm1.timestamp, dm1.sensor_output, dm2.sensor_output
答案 1 :(得分:2)
您可以使用aliases建立相同表格之间的关系。
您的查询可能就像
adalias1 = aliased(DataMeasurement)
adalias2 = aliased(DataMeasurement)
q1 = self.session.query(DataMeasurement).\
filter(
and_(
adalias1.data_source in ('Sensor1', 'Sensor2'),
adalias1.timestamp == adalias2.timestamp
)
)