【问题标题】:SQL query to select all rows with a value included in an arraySQL 查询以选择具有包含在数组中的值的所有行
【发布时间】:2023-01-02 03:51:59
【问题描述】:

我有一个数组 projectIdsids。我想从数据库中选择数组中存在的值为 project_id 的所有行:

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,
    }
);

查询返回UnhandledPromiseRejectionWarning: Error。这段代码有什么问题?

【问题讨论】:

  • ${projectIds} 计算结果为 '1,2,3,4' 没有括号。如果安全的话,也许你可以直接在 SQL 中编写数组 WHERE project_id IN [1,2,3,4]
  • 谢谢,我试了一下,还是报错。

标签: sql node.js sequelize.js


【解决方案1】:

试试这个:

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 = (:projectIds)',
    {
        replacements: projectIds,
        type: QueryTypes.SELECT,
    }
);

【讨论】:

    猜你喜欢
    • 2021-11-21
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 2010-09-13
    • 2020-11-25
    • 1970-01-01
    • 2016-01-21
    相关资源
    最近更新 更多