Sequelize query with NOT IN clause and nested SELECT

こ雲淡風輕ζ 提交于 2021-02-11 17:38:54

问题


I have an SQL query which I would like to express using the sequelize query syntax.

DB Scheme

  • Users: (id, username, ...)
  • Groups: (id, name, ...)
  • User_Groups: (id, #groupId, #userId)

Query Description

Retrieve all users that are not yet part of a particular group.

Raw SQL Query (working)

SELECT User.id, User.email FROM Users as User 
  WHERE User.id NOT IN (
    SELECT User_Group.userId FROM User_Groups as User_Group 
    WHERE User_Group.groupId = ${groupId}
  )

Where I'm blocked

I tried to simulate a join using the sequelize include statement, but my brain is stuck transforming the nested SELECT query as well as the NOT IN operator...


回答1:


It's not possible to represent sub-queries other than using Sequelize.literal in the where clause like this:

const users = await database.User.findAll({
  where: Sequelize.where(Sequelize.literal(`(User.id NOT IN (
    SELECT User_Group.userId FROM User_Groups as User_Group 
    WHERE User_Group.groupId = '${groupId}'
  ))`)
}

or you can mix up Op.notIn with Sequelize.literal



来源:https://stackoverflow.com/questions/63752443/sequelize-query-with-not-in-clause-and-nested-select

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!