我正在尝试在表格中插入用户匹配,但我不想重复。 因此,我正在运行 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/