首页 文章

Sequelize - where子句中的子查询

提问于
浏览
16

我在我的Express应用程序中使用Sequelize . 我需要生成一个在 WHERE 子句中有子查询的查询 .

SELECT *
  FROM MyTable
 WHERE id NOT IN (
       SELECT fkey
         FROM MyOtherTable
        WHERE field1 = 1
          AND field2 = 2
          AND field3 = 3
       )

我首先通过我的模型尝试过关系/关联,但无法让它发挥作用 . 就像是:

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() ,那里没有运气 .

然后我尝试了 Sequelize.literal() ,这有效但不确定它是否是在Sequelize的where子句中做子查询的方式,因为我是新手 .

MyTable.find( {
    where: {
        id: {
            $notIn: sequelize.literal( 
                '( SELECT fkey ' +
                    'FROM MyOtherTable ' +
                   'WHERE field1 = ' + field1 +
                    ' AND field2 = ' + field2 +
                    ' AND field3 = ' + field3 + 
                ')'
        }
    } 
} );

我也知道我可以使用 Sequelize.query() ,但不知道我是否应该达到它或者是否 literal() 就在我身边,因为我觉得's something I'可以俯视 .

我真的想知道如何使用Sequelize "proper"方式在 WHERE 子句中执行子查询 .

感谢您的反馈!

1 回答

  • 15

    我在我的项目中遇到过类似的问题 . 我选择实现它的方式有点不同,原因有两个:

    • 如果在某个时间点Sequelize决定实施子查询 - 语法就绪 .

    • 再次使用Sequelize保护SQL注入 .

    这是我的代码片段,希望它有所帮助 .

    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: {
                 $notIn: sequelize.literal('(' + tempSQL + ')'),
            }
        } 
    } );
    

    有些人可能会选择不使用tempSQL变量,只是在find结构中构建SQL(也许使用帮助器方法?)

    我也认为这可能是sequelize的子查询扩展的基础,因为它几乎使用相同的语法 .

相关问题