我有两个表,sensors
和readings
。我需要在sensors
中列出readings
中最新值的所有条目。 readings
表有一个指向sensors
的外键。我如何用Sequelize实现这一目标?
以下是应该发生的事情:
sensors:
---------------
| id | name |
---------------
| 1 | Test |
---------------
| 2 | Test 2 |
---------------
readings:
---------------------------------------------
| id | sensor | value | time |
---------------------------------------------
| 1 | 2 | 25.5 | 2016-06-14 17:01:50 |
---------------------------------------------
| 2 | 2 | 23.5 | 2016-06-14 17:04:50 |
---------------------------------------------
| 3 | 1 | 21.7 | 2016-06-14 17:06:00 |
---------------------------------------------
result:
---------------------------------------------
| id | name | value | time |
---------------------------------------------
| 1 | Test | 21.7 | 2016-06-14 17:06:00 |
---------------------------------------------
| 2 | Test 2 | 23.5 | 2016-06-14 17:04:50 |
---------------------------------------------
答案 0 :(得分:0)
我认为您可以使用sequelizejs
的{{3}}来执行此操作;)
sequelize.query(
'select s.*, r.value, r.time' +
'from sensors s ' +
'left join readings r on s.id = r.sensor' +
'and (r.sensor, r.time) in (' +
'select sensor, max(time) from readings group by sensor' +
')',
{type : sequelize.QueryTypes.SELECT})
.then(function(result) {
console.log(result);
});
答案 1 :(得分:0)
假设您正确建模关系,您应该能够执行如下查询:
models.sensors.findAll({
include: [{
model: models.readings,
order: [['time', 'DESC']],
limit: 1
}],
order: [['id', 'ASC']]
}).then(results => results.map(result => {
return {
id: result.id,
name: result.name,
value: result.readings[0].value,
time: result.readings[0].time
}
})).then(results => {
// The rest of your logics here...
})