简体   繁体   中英

Sequelize Select column WHERE other column has not contain value

I have the following Accounts_Users table :

account_id | user_id
--------------------
1          | 60
2          | 60
1          | 50
3          | 50 

And I want to retrieve all the user_id's which do not have rows with certain account_id For example, if the account_id = 2 I want the result should be:

user_id
-------
50 

Since user_id = 60 have record with account = 2.

my current query looks like this:

let existingUserIdsWithAccountUser = await AccountUserModel.findAll({
    raw: true,
    where: {
      account_id: account_id,
      user_id: {
        [Sequelize.Op.in]: existingUsersIds
      }
    },
          attributes: [Sequelize.fn('DISTINCT', Sequelize.col('user_id')), 'user_id']

  }).map(user => user.user_id);
  const existingUserIdsWithoutAccountUser = existingUsersIds.filter(user_id => !existingUserIdsWithAccountUser.includes(user_id));

I want to do a single query without having to filter the results.

I also tired the following:

    let existingUserIdsWithoutAccountUser = await AccountUserModel.findAll({
          raw: true,
          where: {
            account_id: {
              [Sequelize.Op.not]: account_id
            },
            user_id: {
              [Sequelize.Op.in]: existingUsersIds
            }
          },
  attributes: [Sequelize.fn('DISTINCT', Sequelize.col('user_id')), 'user_id']
        }).map(user => user.user_id);
    

but in this case, if I have a record with a different account_id then it still gets returned obviously.

I was finally able to do it using the following query:

const existingUserIdsWithoutAccountUser = 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 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