还有很多其他相关问题,但我无法将它们完全应用于我的情况。我正在使用 sequelize,所以我试图以尽可能少的对数据库的点击来做到这一点。
我的(简化)表基本上是:
id dateAcquired staffId skillId
44 2017-04-27 25 2
341 2018-02-01 28 2
4787 2018-04-04 25 2
8852 2020-01-31 28 2
我正在寻找每个员工 ID 的最近日期获取的 ID。 (请注意,最近的可能是较低的 ID,否则我会有解决方案)
4787
8852
只是在使用此查询的 SQL 中,我得到了正确的日期但不是正确的 id:
SELECT id, staffId, max(`dateAcquired`)
FROM `histories` AS `history`
WHERE `history`.`skillId` = '2'
GROUP BY `staffId`, id
结果是:
44 2018-04-04
341 2020-01-31
虽然我知道一旦我得到正确的查询就需要调整,但我的 Sequelize 代码是:
models.history.findAll(
{
attributes: [sequelize.fn("max", sequelize.col('dateAcquired')), 'id'],
where: {skillId:id},
group: ["id"]
}
).then(maxIds => {
let ids = maxIds.map(result =>{return result.id;});
models.history.findAll({
include: [
{
model:models.staff
}
],
where: {
id: {
[Op.in]: [ids]
}
}
}).then(results =>
{
res.json(results);
})
})
谢谢你的帮助!
最佳答案
使用 NOT EXISTS
:
select h.* from histories h
where h.skillid = 2
and not exists (
select 1 from histories
where skillid = h.skillid and staffid = h.staffid and dateAcquired > h.dateAcquired
)
请参阅 demo 。
结果:
| id | dateAcquired | staffId | skillId |
| ---- | ------------------- | ------- | ------- |
| 4787 | 2018-04-04 00:00:00 | 25 | 2 |
| 8852 | 2020-01-31 00:00:00 | 28 | 2 |
关于mysql - 与组中最大日期关联的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60570967/