获取最后插入元素的ID

时间:2015-04-15 11:24:29

标签: mysql database node.js

基本上我有两张桌子

User -> id, name , email , fname, lname etc...

Device -> id, name, user_id, etc......

首先我将数据插入到User表中,然后得到结果, 从该结果如何获取User表条目的Id,以便我可以使用user_id作为设备中的条目 基本上user_idforeign key引用User

我的插入代码就像这样

exports.user = function(req,res){
var user_email = req.param('email', null);
var user_fname = req.param('fname', null);
var user_lname = req.param('lname', null);
var user_phone = req.param('phone', null);
var user_description = req.param('description',null);

var user_data = {
    table:TABLE_USER,
    data:{
        'email':user_email,
        'fname':user_fname,
        'lname':user_lname,
        'phone':user_phone,
        'description':user_description
    }
}

db.insert(user_data,function (result) {
      //How to get the ID of the last inserted row from result, 
      // get Id and insert in device table
      res.writeHeader(200, {"Content-Type": "text/plain"});
      res.write(result[0] + " ");
      res.end();    
    }
    );
}

1 个答案:

答案 0 :(得分:1)

请查看文档:{​​{3}}

他们的代码示例:

connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result) {
  if (err) throw err;

  console.log(result.insertId);
});