与LAST_INSERT_ID相关的MySql错误需要解决方法

时间:2011-12-15 05:28:16

标签: mysql

我正在处理一个存储过程,它将数据插入到多个表中,获取最后插入的id并将其存储在另一个表中。我遇到了与Mysql 5.0.24中的LAST_INSERT_ID错误有关的问题

reference

此问题是否有可行的解决方法?

例如。

// 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);

问题是当插入代理时,orderId从代理表

获取id

1 个答案:

答案 0 :(得分:3)

基本上你必须找到一些从新插入的行获取orderId的方法,可以通过timestamp(锁定表以便确保这是表中的最新行)或其他方式。在这种情况下,它可以正常使用这样一个事实:这个代理只能有一行,因为代理刚刚创建,并且不可能在之前添加另一个订单。

我用某种伪代码写了这个

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();
}