【问题标题】:Update mysql database with array condition使用数组条件更新 mysql 数据库
【发布时间】:2018-08-20 11:19:03
【问题描述】:

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

const myIds = [2, 3, 4];

我也有这样一个数据库:

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

我想更新我的数据库,以便我的数组中所有 id 的 seen 列都设置为 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");
    });

还有其他方法吗?

感谢您的帮助。

【问题讨论】:

    标签: javascript mysql arrays node.js


    【解决方案1】:

    感谢@cdaiga,我设法让它工作了:

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

    【讨论】:

      【解决方案2】:

      试试这个:

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

      【讨论】:

      • 我遇到了这个错误:Error: ER_TRUNCATED_WRONG_VALUE: Truncated incorrect DOUBLE value: '2,3,4'
      猜你喜欢
      • 1970-01-01
      • 2014-10-21
      • 2014-04-04
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多