节点mysql插入到多对多表

时间:2022-03-05 09:58:34

I'm using nodejs to parse a csv file and save information about it in mysql. I'm trying to insert data to a many to many table but want the id's inserted to the database to be used in a anohter query?

我正在使用nodejs来解析csv文件并在mysql中保存有关它的信息。我正在尝试将数据插入到多个表中,但是希望将id插入数据库以用于anohter查询?

con.query("INSERT INTO TransactionDescription SET ? ON DUPLICATE KEY UPDATE Description= VALUES(Description)", trandesc, function(err, res) {
                            if (err) throw err;


                        });

can i return the id's generated so i can use them in this query ?

我可以返回生成的id,以便我可以在此查询中使用它们吗?

  con.query("INSERT INTO Transaction SET ? ", tran, function(err, res) {
                            if (err) throw err;
                        });

2 个解决方案

#1


1  

If you are using node-mysql, you can simply get the inserted id like this (see doc) :

如果你使用的是node-mysql,你可以像这样简单地获取插入的id(参见doc):

con.query("INSERT INTO TransactionDescription SET ? ON DUPLICATE KEY UPDATE Description= VALUES(Description)", trandesc, function(err, res) {
  if (err) throw err;
  // res.insertId from above query as second query parameter
  con.query("INSERT INTO Transaction SET ? ", res.insertId, function(err, res) {
    if (err) throw err;
  });
});

#2


0  

I'd recommend to use knex.js which simplifies writing queries a lot. Also it easily allows you to access the generated id's, e.g.

我建议使用knex.js,它简化了大量编写查询的过程。此外,它还可以轻松访问生成的ID,例如

knex.insert({
  first_name: firstName,
  last_name: lastName,
  email: email,
  phone_number: phoneNumber
})
.returning('id')
.into('person')
.then(function (id) {
  // use id here
});

#1


1  

If you are using node-mysql, you can simply get the inserted id like this (see doc) :

如果你使用的是node-mysql,你可以像这样简单地获取插入的id(参见doc):

con.query("INSERT INTO TransactionDescription SET ? ON DUPLICATE KEY UPDATE Description= VALUES(Description)", trandesc, function(err, res) {
  if (err) throw err;
  // res.insertId from above query as second query parameter
  con.query("INSERT INTO Transaction SET ? ", res.insertId, function(err, res) {
    if (err) throw err;
  });
});

#2


0  

I'd recommend to use knex.js which simplifies writing queries a lot. Also it easily allows you to access the generated id's, e.g.

我建议使用knex.js,它简化了大量编写查询的过程。此外,它还可以轻松访问生成的ID,例如

knex.insert({
  first_name: firstName,
  last_name: lastName,
  email: email,
  phone_number: phoneNumber
})
.returning('id')
.into('person')
.then(function (id) {
  // use id here
});