使用mysql和nodeJs更新多个记录

时间:2018-03-08 09:41:42

标签: mysql node.js sequelize.js

我正在尝试使用NodeJS和Sequelize更新满足特定条件的多个记录。例如,如果student_id为1且advisor_id为1,则将score设置为90,如果student_id为1且advisor_id为2,则将得分设置为80,依此类推....每个学生由3位顾问评估。在我的得分表中,我有 id,student_id,advisor_id,得分

以下是用户传递的示例JSON数据。

 {
      "students": [
          {
            "student_id": 1,
            "committee": [
                { "advisor_id": 1, "score": 90 },
                { "advisor_id": 2, "score": 80 },
                { "advisor_id": 3, "score": 90 },
              ]
          },
          {
            "student_id": 2,
            "committee": [
                { "advisor_id": 1, "score": 70 },
                { "advisor_id": 2, "score": 70 },
                { "advisor_id": 3, "score": 80 },
              ]
          },
          {
            "student_id": 3,
            "committee": [
                { "advisor_id": 1, "score": 90 },
                { "advisor_id": 2, "score": 70 },
                { "advisor_id": 3, "score": 70 },
              ]
          },
          {
            "student_id": 4,
            "committee": [
                { "advisor_id": 1, "score": 80 },
                { "advisor_id": 2, "score": 90 },
                { "advisor_id": 3, "score": 80 },
              ]
          },

        ]  
    }

1 个答案:

答案 0 :(得分:1)

你可以这样做:

var queries = '';

  values.forEach(function (item) {
    queries += mysql.format("UPDATE tabletest SET score = 90 WHERE 
  student_id = 1 AND advisor_id = 1;");
    queries += mysql.format("UPDATE tabletest SET score = 80 WHERE 
  student_id = 1 AND advisor_id = 2;");
  });

  connection.query(queries, defered.makeNodeResolver());

要使用多个语句功能,您必须为连接启用它:

var connection = mysql.createConnection({
  ...
  multipleStatements: true,
});