【问题标题】:Sequelize - subquery in where clauseSequelize - where 子句中的子查询
【发布时间】:2016-07-09 22:45:47
【问题描述】:

我在我的 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() 是否适合我,因为我觉得我忽略了一些东西。

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

感谢您的反馈!

【问题讨论】:

标签: orm subquery where-clause sequelize.js


【解决方案1】:

除了@Shahar Hadas 的回答,因为我在使用他展示的代码时遇到了一些错误。

这是一个更复杂的例子。在这个例子中,我们有一个名为“Artist”的主表,它与“Tag”处于多对多关系中。 “标签”与我命名为“TagType”的预定义标签列表相关联。 我们想要获取链接到所有搜索标签(TagType Id)的所有艺术家。

const tagsSearched = [1, 2];

const subQueryOptions = {
    attributes: ['id'], // You have to list at least one attribute
    include: [
        {
            model: models.Tag,
            required: true,
            attributes: [], // Avoid the only_full_group_by error
            through: {
                attributes: [], // Avoid the only_full_group_by error
            },
            include: {
                model: models.TagType,
                required: true,
                attributes: [], // Avoid the only_full_group_by error
                where: {
                    id: {
                        [Op.in]: tagsSearched, // Array of tags searched
                    }
                },
            },
        }
            ],
    group: sequelize.col('artist.id'), // Group by the main parent ID of this query
    having: sequelize.where(sequelize.fn('count', 
            sequelize.col('tags.tagType.id')), {
                [Op.gte]: tagsSearched.length,
    }), // Get only the artists that have at least the "tagsSearched" associated
}

// Parse the subQueryOptions, this operation would serialize the queryOptions
Model._validateIncludedElements.bind(models.Artist)(subQueryOptions);

// First argument has to be a string (table name, by default in plural)
// Second argument is our serialized query options
// Third argument is the model used
const artistsSubQuery = sequelize.dialect.queryGenerator.selectQuery("artists", subQueryOptions, models.Artist)
.slice(0,-1); // to remove the ';' from the end of the SQL query

models.Artist.findAll({
    where: {
        id: {
            [Op.in]: sequelize.literal(`(${artistsSubQuery})`),
        }
    }
});

如有问题,我会更新。

【讨论】:

    【解决方案2】:

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

    1. 如果 Sequelize 在某个时间点决定实施子查询 - 语法已准备就绪。
    2. 对 SQL 注入使用 Sequelize 保护。

    这是我的代码 sn-p,希望对您有所帮助。

    续集 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(也许使用辅助方法?)

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

    【讨论】:

    • SQL 生成器和查找查询中的 where 对象是否可以安全地互换?我可以在这里和那里使用相同的语法吗?
    • ASFAIK 是的。 find 方法在内部使用 QueryGenerator。这就是我首先采用这种方法的原因。
    • 谢谢。当我需要将限制/偏移与where 一起用于包含的模型时,这救了我。我生成了一个像你在这里展示的子查询,它就像魅力一样工作。
    • 我正在使用 v6 但 getDialect() 方法无法使用
    • @ShaharHadas 我明白了,我在这里更彻底地阅读了其他 cmets,我能够使用 Sequelize 实例来做到这一点。谢谢!现在点赞答案! :)
    猜你喜欢
    • 2021-06-16
    • 2019-03-09
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 2018-01-08
    • 2020-12-31
    相关资源
    最近更新 更多