mysql - 如果找不到 ID,如何插入行?

标签 mysql node.js

我正在尝试在表格中插入用户匹配,但我不想重复。 因此,我正在运行 COUNT 查询,但是当我尝试插入新记录时,我得到了未定义,所以我无法插入记录。

我读过有关使用回调的信息,但我对 NodeJS 还很陌生,目前正在苦苦挣扎。

if(user_matches.length !== 0){
    var connection = mysql.createConnection({
        'host': 'localhost',
        'user': 'root',
        'password': '',
        'database': 'test'
    });

    connection.connect();

    //connection.query('TRUNCATE matches');
    // I was originally truncating the table, but this just doesn't cut it

    for (var x = 0; x < user_matches.length; x++){
        var countQuery = connection.query('SELECT COUNT(*) as count FROM matches WHERE user_id_1 = ?', [ user_matches[x]['user_1']['id'] ]);
        countQuery.on('result', function(){

            // Here I get the UNDEFINED error, can't insert
            connection.query('INSERT INTO matches SET ?', {
                'user_id_1': user_matches[x]['user_1']['id'],
                'user_id_2': user_matches[x]['user_2']['id']
            });

        });
    }

    connection.end();
}

最佳答案

安装async

npm install async --save

然后试试这个:

if(user_matches.length !== 0){
 var connection = mysql.createConnection({
      'host': 'localhost',
      'user': 'root',
      'password': '',
      'database': 'test'
  });

  connection.connect();

  async.each(user_matches, function(x, callback){
    var countQuery = connection.query('SELECT COUNT(*) as count FROM matches WHERE user_id_1 = ?', [ x['user_1']['id'] ]);

    countQuery.on('result', function(){
      var insertQuery = connection.query('INSERT INTO matches SET ?', {
          'user_id_1': x['user_1']['id'],
          'user_id_2': x['user_2']['id']
      });

      insertQuery.on('result', callback);

    });
  }, function(err){
    console.log('done');
  });
}

关于mysql - 如果找不到 ID,如何插入行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32364460/

相关文章:

node.js - 运行 vs-mda-remote 时出错

javascript - 用 Jest 和 sequelize-mock 模拟 Sequelize

javascript - Node.js、mongoose 和 MongoDb - 替换多个文档中特定字符串中的字符

MySQL运行时报错 `rails server`

c# - 使用 MySql、EF 和 CF 的慢速查询

java - 如何获取结果集中的上一个项目?

javascript - 使用 Express 和 Grunt 进行 Mocha 测试

php - MYSQL PHP 删除 'Couldn' t 执行查询 :'

php - 如何在 Wordpress Gravity Forms 中使用 PHP 创建条目

Django、socket.io、node.js - 管理私有(private)消息和群组对话