簡體   English   中英

獲取 node.js 中的最后一個插入 ID 並將其傳遞給第二個查詢

[英]get the last insert id in node.js and pass it to a second query

我的 sql 數據庫中有 2 個表,一個名為 club 的表和一個名為 players 的表,它們通過一對多關系連接,node.js 中的查詢工作正常但我無法獲得 table club 的最后插入,我需要它用於插入表玩家的外鍵

here what i have tried in node.js:



       module.exports={
 create:(data,callback)=>{
  var myArray = new Array();
 /* for(let item of data.players) {
    console.log(item.firstname);
}*/

data.players.forEach((player) => {
  console.log(player.id);
  console.log(player);
  var playerModel ={
    id : player.id,
    firstname : player.firstname,
    lastname : player.lastname,
    position : player.position,
    price : player.price,
    appearences : player.appearences,
    goals : player.goals,
    assists : player.assists,
    cleansheets : player.cleansheets,
    redcards : player.redcards,
    yellowcards : player.yellowcards,
    image : player.image,
    clubid : player.clubid,
  };
  console.log("model"+playerModel.position);
  myArray.push(playerModel);
});
var id;
 
 pool.query(
      'insert into club(userid,name,price) values(?,?,?)',
   [
        data.userid,
        data.name,
        data.price
      ],
    
      (error,result) => {
        if(error){
          callback(error);
         
        }
     /*   id = result.insertId;
        console.error(result);
        console.log(result+"  result");*/
        
        console.log(result.insertId);
        return callback(null,result.insertId);
      },

      
    );



    for(var item of myArray){
    pool.query(
      
      'insert into players(id,firstname,lastname,position,price,appearences,goals,assists,cleansheets,redcards,yellowcards,image,clubid) values (?,?,?,?,?,?,?,?,?,?,?,?,?)',
       [ 
       item.id,
       item.firstname,
       item.lastname,
       item.position,
       item.price,
       item.appearences,
       item.goals,
       item.assists,
       item.cleansheets,
       item.redcards,
       item.yellowcards,
       item.image,
       (
        'select top 1 id from club order by id desc'
        )
       ],
      
 
     (error,results,fields)=>{
       if(error){
         callback(error);
       }
       return callback(null,results);
     },
    );
    }
  },
     

不知道該怎么做

創建一個多查詢批處理,例如

INSERT INTO table1 (column1, column2, column3) VALUES (?, ?, ?);
INSERT INTO table2 (column1, reference_column, column3) VALUES (?, LAST_INSERT_ID(), ?);

使用以下方法執行:

  1. 支持多查詢批量執行
  2. 將批處理作為事務執行

參數作為一個實心數據數組提供給此方法(對於顯示的代碼,它將包含 5 個值,前 3 個將插入到第一個查詢中,所有另一個都插入到第二個)。 第一個查詢分配的id值將由 function 自動檢索並插入到第二個查詢中。


我不知道 Node.JS 中描述屬性的方法是什么。 但它必須存在..

如果我理解正確,子查詢應該在這里工作。

-- first insert the club from paraterized query
insert into club (clubid, name, price) 
values (? , ? , ?);


-- then use a subquery to find the last inserted club id
insert into
   players (id, firstname, lastname, position, price, appearences, goals, assists, cleansheets, redcards, yellowcards, image, clubid) 
values
   (
       ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , 
      (
         select clubid 
         from club 
         order by clubid desc
         limit 1
      )
   )
;

除此之外,插入語句不會返回任何數據。 如果您希望從 NodeJS 中的第一次調用中獲取 ID,則需要運行批處理語句。 1 個插入和 1 個 select,在發送到 SQL 服務器的同一批語句中。 在此處查看多語句配置的更多信息。 node-mysql 一次查詢多條語句

const pool = mysql.createConnection({multipleStatements: true});
pool.query(`
  insert into club(userid,name,price) values(?,?,?);
  select clubid from club order by clubid desc limit 1;
  `
  , params
  , function(err, results) {
  if (err) throw err;
    // now the id will be the second item of the batch statement result
    const myId = results[1]
});
)

實際上,基於這兩件事,您可以將它們結合起來。

pool.query(`
  insert into club(userid,name,price) values(?,?,?);
  insert into players (id, firstname, lastname, position, price, appearences, goals, assists, cleansheets, redcards, yellowcards, image, clubid) 
  values
   (
       ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , 
      (
         select clubid 
         from club 
         order by clubid desc
         limit 1
      )
   );
  `
  , params
)

您也可以為此創建自己的存儲過程。

解決這個問題的另一種方法是將包含第一個 INSERT 語句的初始查詢放入變量中:

const first_insert = db.query('INSERT')...

然后返回第一個 promise 末尾的變量,然后找到變量的屬性值(因為它返回一個 javascript object 畢竟):

.then((first_insert) => {
   console.log(Object.entries(first_insert)); //returns array
   console.log(first_insert[0]); 
/*returns contents of first index of previously returned array, you'll see an object with a insertId property, thats what you need*/
   console.log(first_insert[0].insertId) 
/*this is the value you need to pass to each following statement*/
/*store that value in a variable that you declarre before any of the db methods, I named mine pk*/
   pk = first_insert[0].insertId
/*Now use that variable for the foreign key and to correspond with the placeholder in whatever queries you use*/
}

如何在 NodeJS 中使用它,oracle? 我的錯誤是錯誤:ORA-00933:SQL 命令未正確結束。

-- 首先將俱樂部從參數化查詢插入到俱樂部(俱樂部標識、名稱、價格)值(?、?、?);

-- 然后使用子查詢查找最后插入的俱樂部 ID insert into players (id, firstname, lastname, position, price, appearences, goals, assists, cleansheets, redcards, yellowcards, image, clubid) values (?, ?, ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , (select clubid from club order by clubid desc limit 1 ) );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM