Home > other >  SQL query to select all rows with a value included in an array
SQL query to select all rows with a value included in an array

Time:01-03

I have an array projectIds with ids. I want to select all rows from a database that have a value for project_id that exists in the array:

const { sequelize } = require("./db");  //The db and sequelize work correctly in other places, so can be assumed to be set up correctly.
const { QueryTypes } = require("sequelize");

const projectIds = [1,2,3,4];

let rows = await sequelize.query(
    "SELECT * FROM `table_name` WHERE project_id IN = ?",
    {
        replacements: [`${projectIds}`],
        type: QueryTypes.SELECT,
    }
);

The query returns UnhandledPromiseRejectionWarning: Error. What is wrong with this code?

CodePudding user response:

You should use (?) or (:projectIds) instead of ? and pass the projectIds array as is:

let rows = await sequelize.query(
    "SELECT * FROM `table_name` WHERE project_id IN (?)",
    {
        replacements: [projectIds],
        type: QueryTypes.SELECT,
    }
);

OR

let rows = await sequelize.query(
    "SELECT * FROM `table_name` WHERE project_id IN = (:projectIds)",
    {
        replacements: { projectIds },
        type: QueryTypes.SELECT,
    }
);
  • Related