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

Mysql 如果找不到ID,如何插入行?,mysql,node.js,Mysql,Node.js,我试图在表中插入用户匹配项,但不想重复。 因此,我正在运行计数查询,但当我尝试插入新记录时,我得到了未定义的,因此无法插入该记录 我读过关于使用回调的书,但由于对NodeJS还相当陌生,我目前正在努力 if(user_matches.length !== 0){ var connection = mysql.createConnection({ 'host': 'localhost', 'user': 'root', 'password':

我试图在表中插入用户匹配项,但不想重复。 因此,我正在运行计数查询,但当我尝试插入新记录时,我得到了未定义的,因此无法插入该记录

我读过关于使用回调的书,但由于对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();
}
if(用户匹配.length!==0){
var connection=mysql.createConnection({
'主机':'本地主机',
'用户':'根',
“密码”:“,
“数据库”:“测试”
});
connection.connect();
//query('TRUNCATE matches');
//我本来是要截断桌子的,但这并不能切断它
对于(var x=0;x
安装
async

npm安装异步--保存

然后试试这个:

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');
  });
}

好吧,这是一个问题。我现在有另一个问题,它是说“调用exit后无法将查询排队”:(@user2864740控制流有问题,但他只是执行计数插入,所以没有竞争条件。@MauroCasas问题是连接。end()正在查询完成之前被调用。您需要使用类似于
async
库的内容,而不是
for循环
,并在所有查询完成后调用connection.end()。搜索“mysql upsert”。可能重复