Sequelize - where 子句中的子查询 [英] Sequelize - subquery in where clause
问题描述
我在我的 Express 应用中使用 Sequelize.我需要生成一个在 WHERE
子句中有一个子查询的查询.
I'm using Sequelize in my Express app. I need to generate a query that has a subquery in the WHERE
clause.
SELECT *
FROM MyTable
WHERE id NOT IN (
SELECT fkey
FROM MyOtherTable
WHERE field1 = 1
AND field2 = 2
AND field3 = 3
)
我首先通过我的模型尝试了关系/关联,但无法让它发挥作用.类似的东西:
I first tried relations/associations through my models but couldn't get it to work. Something like:
MyTable.find( {
where: {
id: {
$notIn: // <= what goes here? Can I somehow reference my include model?
}
},
include: [ {
model: MyOtherTable,
where: {
field1: 1,
field2: 2,
field3: 3
} ]
} );
然后我尝试使用 Sequelize.where()
,但没有成功.
Then I tried using Sequelize.where()
, no luck there.
然后我尝试了 Sequelize.literal()
并且它有效,但不确定它是否是在 Sequelize 的 where 子句中执行子查询的正确" 方式,就像我一样刚接触它.
Then I tried Sequelize.literal()
and that works but not sure if it's a "proper" way of doing a subquery in a where clause in Sequelize as I'm new to it.
MyTable.find( {
where: {
id: {
$notIn: sequelize.literal(
'( SELECT fkey ' +
'FROM MyOtherTable ' +
'WHERE field1 = ' + field1 +
' AND field2 = ' + field2 +
' AND field3 = ' + field3 +
')'
}
}
} );
我也知道我可以使用 Sequelize.query()
但我真的不知道我是否应该使用它或者 literal()
是不是马上因为我觉得我忽略了一些东西.
I also know that I could use Sequelize.query()
but don't really know if I should reach for it or if literal()
is the right away as I feel like there's something I'm overlooking.
我真的很想知道如何在 WHERE
子句中使用 Sequelize 正确" 方式执行子查询.
I would really like to know how to perform a subquery in a WHERE
clause with Sequelize the "proper" way.
感谢您的反馈!
推荐答案
我在我的项目中遇到了类似的问题.我选择实现它的方式有点不同,原因有两个:
I have encountered a similar issue in my project. The way I choose to implement it is a bit different for two reasons:
- 如果在某个时间点 Sequelize 决定实施子查询 - 语法已准备就绪.
- 使用 Sequelize 保护来防止 SQL 注入.
这是我的代码片段,希望对您有所帮助.
Here is my code snippet, hope it helps.
Sequelize v5
const tempSQL = sequelize.dialect.QueryGenerator.selectQuery('MyOtherTable',{
attributes: ['fkey'],
where: {
field1: 1,
field2: 2,
field3: 3
}})
.slice(0,-1); // to remove the ';' from the end of the SQL
MyTable.find( {
where: {
id: {
[Sequelize.Op.notIn]: sequelize.literal(`(${tempSQL})`)
}
}
} );
续集 v6
const tempSQL = sequelize.dialect.queryGenerator.selectQuery('MyOtherTable',{
attributes: ['fkey'],
where: {
field1: 1,
field2: 2,
field3: 3
}})
.slice(0,-1); // to remove the ';' from the end of the SQL
MyTable.find( {
where: {
id: {
[Sequelize.Op.notIn]: sequelize.literal(`(${tempSQL})`)
}
}
} );
有些人可能会选择不使用 tempSQL 变量,而只是在 find 结构中构建 SQL(也许使用辅助方法?)
Some people might choose to not use the tempSQL variable and simply build the SQL inside the find structure (maybe using a helper method?)
我也认为这可能是 sequelize 的子查询扩展的基础,因为它几乎使用相同的语法.
I also think this might be the basis for a sub queries extension for sequelize as it uses the same syntax almost.
这篇关于Sequelize - where 子句中的子查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!