我有一个数据库,有一堆不同的列。假设它看起来像这样:
TABLE: dbtable
__________________________________
| onecolumn | id | twocolumn |
|---------------------|------------|
| some | 1 | matchthis |
| random | 2 | dontmatch |
| thing | 3 | matchthis |
| here | 4 | dontmatch |
|__________________________________|
我还有一个 Node.js 程序(使用 Sequelize),它应该对 dbtable
表进行排序,并找到具有最高 ID 值的行,以及两列等于“matchthis”的行. (所有这些值都是示例)。
代码如下所示:
const rel = await dbtable.findOne({
where: {
twocolumn: req.params.twocolumn // Url param that equals "matchthis"
},
order: Sequelize.fn('max', Sequelize.col('id')),
});
但是,它没有返回 {"onecolumn": "thing", "id": "3", "twocolumn": "matchthis"}
,而是返回此错误:
SequelizeDatabaseError: Expression #1 of ORDER BY contains aggregate function and applies to the result of a non-aggregated query
我不太擅长数据库,而且我似乎无法弄清楚发生了什么。
答案 0 :(得分:0)
您的查询不包含 GROUP BY
子句,使其成为错误提示的“非聚合查询”,使其与聚合函数 (MAX()
) 的排序不兼容。
您可以直接在 id
列上订购。
const rel = await dbtable.findOne({
where: {
twocolumn: req.params.twocolumn
},
order: [
[ 'id', 'DESC' ]
]
});