2011-12-15 93 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(); 
}