2011-12-15 80 views
0

我正在研究將數據插入多個表的存儲過程,獲取最後插入的id並將其存儲在另一個表中。我被困在問題在MySQL 5.0.24與LAST_INSERT_ID相關的MySql錯誤需要解決方法

reference

相關LAST_INSERT_ID錯誤是否有任何可能的辦法解決這個問題呢?

例如,

// if agent is new one 

INSERT INTO `agent`(`agn_name`, `agn_cus_id`) VALUES (agentName, customerId); 
SET agnId = LAST_INSERT_ID(); 

//else get agnId = existing one 

INSERT INTO `order`(`orderno`, `description`, `agent`) VALUES (orderNo, description,  agnId); 

SET orderId = LAST_INSERT_ID(); 

INSERT INTO `suborder1`(`orderid`, `description`) VALUES(orderId, subdescription1); 

INSERT INTO `suborder2`(`orderid`, `description`) VALUES(orderId, subdescription2); 

問題是,當代理得到插入,訂單ID獲取的ID從代理表

+0

你知道錯誤是5年前關閉?您使用的數據庫多大? – 2011-12-15 05:31:13

+0

請發佈一些代碼,當前數據和預期數據 – Nonym 2011-12-15 05:35:18

回答

3

基本上,你必須找出在新插入的行獲得訂單ID的某種方式,或者通過時間戳(鎖表,以便你可以確定這是表中最新的一行)或其他東西。在這種情況下,它可以很好地使用這樣的事實,即只有一行才能爲該代理創建代理,並且不可能在先前添加其他訂單。

我在某種僞代碼編寫這個

if (agent is new one) { 
    INSERT INTO agent(agn_name, agn_cus_id) VALUES (agentName, customerId); 
    SET agnId = LAST_INSERT_ID(); 
    INSERT INTO order(orderno, description, agent) VALUES (orderNo, description, agnId); 
    -- there can only be one row in order for this new agent, as the agent was just created 
    SET orderId = SELECT orderId FROM order WHERE agent = agnId; 
} 
else { 
    SET agnId = <some existing value>; 
    INSERT INTO order (orderno, description, agent) VALUES (orderNo, description, agnId); 
    -- this is the first call to LAST_INSERT_ID() since the agent wasn't created 
    SET orderId = LAST_INSERT_ID(); 
}