2016-06-14 38 views
1

我有两个表,sensorsreadings。我需要列出sensors中的所有条目,其中最新的值为readingsreadings表有一个指向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

@ LT-具有最新时间值的那个。 – MikkoP

回答

0

我认为你可以使用的sequelizejsRaw queries做到这一点;)

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); 
}); 
+0

感谢您的回复。我正在使用Sequelize,因为我试图避免使用原始查询。我相信有一个更好的方法来做到这一点。 – MikkoP

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... 
}) 
+0

感谢您的回复。据我所知,这似乎导致正确的值,但它执行的查询是非常复杂的,并在数据库中有更多的条目,我相信它会很慢。任何其他想法? – MikkoP

+0

你可以尝试使用分页。因此,不要一次加载所有内容(这会很慢),请尝试通过调整极限和偏移量将它们分隔到不同的页面中 – 2016-06-15 12:27:58

+0

分页导致更快的查询,但它不是我尝试的好解决方案实现。 – MikkoP

相关问题