简体   繁体   中英

Convert SQL query with subquery to Sequelize query

I'm new to sequelize and I want to convert the following SQL query :

select distinct user_id
from accounts_users
where user_id not in (
    select user_id
    from accounts_users
    where account_id = 2)

To a Sequelize query but I could not find a way to make the subquery right.

My try that does not work:

const existingUserIdsWithAccountUser = await AccountUserModel.findAll({
      raw: true,
      where: {
        user_id: {
          [Sequelize.Op.and]: {
            [Sequelize.Op.notIn]: Sequelize.literal(`SELECT user_id FROM 'Accounts_Users' WHERE account_id = ${account_id}`),
            [Sequelize.Op.in]: existingUsersIds
          }
        }
      },
      attributes: [Sequelize.fn('DISTINCT', Sequelize.col('user_id')), 'user_id']
    }).map(user => user.user_id);

The query is equivalent to:

select distinct user_id
from accounts_users
where account_id <> 2

Let me know if I am missing anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM