代码之家  ›  专栏  ›  技术社区  ›  nsayer

使用数组条件更新mysql数据库

  •  0
  • nsayer  · 技术社区  · 7 年前

    我有一个唯一ID数组,如下所示:

    const myIds = [2, 3, 4];
    

    我还有一个这样的数据库:

    +-----+------+
    | id  | seen |
    +-----+------+
    |   0 |    0 |
    |   1 |    0 |
    |   2 |    0 |
    |   3 |    0 |
    |   4 |    0 |
    +------------+
    

    我想更新我的数据库,以便 seen 数组中所有ID的列都设置为1。这将给我留下这样的印象:

    +-----+------+
    | id  | seen |
    +-----+------+
    |   0 |    0 |
    |   1 |    0 |
    |   2 |    1 |
    |   3 |    1 |
    |   4 |    1 |
    +------------+
    

    我尝试了此代码,但它只更新了一个条目:

        db.query('UPDATE table SET seen = 1 WHERE id = ?', myIds,
        function (error, results) {
            if (error) throw error;
            console.log("ok");
        });
    

    还有其他方法吗?

    谢谢你的帮助。

    2 回复  |  直到 7 年前
        1
  •  1
  •   cdaiga    7 年前

    尝试以下操作:

    db.query('UPDATE `table` SET seen = 1 WHERE id IN (?)', [myIds.join()],
        function (error, results) {
            if (error) throw error;
            console.log("ok");
        }
    );
    
        2
  •  1
  •   nsayer    7 年前

    感谢@cdaiga我成功地做到了:

    db.query('UPDATE table SET seen = 1 WHERE id IN (?)', [myIds],
        function (error, results, fields) {
            if (error) throw error;
            console.log("ok");
    });