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

时间:2018-03-12 12:25:12

标签: javascript mysql arrays node.js

我有一系列独特的ID,如下所示:

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

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

seen

我想更新我的数据库,以便将我数组中所有ID的+-----+------+ | id | seen | +-----+------+ | 0 | 0 | | 1 | 0 | | 2 | 1 | | 3 | 1 | | 4 | 1 | +------------+ 列设置为1.这样就可以了:

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

我尝试过这段代码,但只更新了一个条目:

using (var httpClientHandler = new HttpClientHandler())
{
  httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
  using (var client = new HttpClient(httpClientHandler))
  {
    client.BaseAddress = new Uri(url);  
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response = await client.PostAsJsonAsync(
"api/token", vm);
    var result = await response.Content.ReadAsStringAsync();
    response.EnsureSuccessStatusCode();
    return Ok(result);
  }
}

还有其他方法吗?

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:1)

谢谢@cdaiga我设法让它发挥作用:

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