问题
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