douliandan7340 2012-05-03 18:12
浏览 187

mysql使用第一个表中的auto_increment值作为第二个中的外键插入到两个表中

I want to insert into the cart table

**orderId** | cartId | cartDate | cartStatus
____________________________________________
1           | 1      | 20120102 | complete
2           | 2      | 20120102 | complete
3           | 3      | 20120102 | complete
4           | 4      | 20120102 | complete

using the auto increment value orderId from the order table

**orderId** | orderStatus | secret   | sauce
____________________________________________
1           | 7          | 020200202 | bbq
2           | 6          | 020200202 | bbq
3           | 6          | 020200202 | t
4           | 4          | 020200202 | m


INSERT INTO ordertable VALUES(null,7,020200202,bbq)

but then using the orderId (which will now be 5)

INSERT INTO carttable VALUES(orderId,20120102,complete)

However, this insert must be done as the same query. If I use mysql_last_id (php) there is an opportunity for someone else to insert into the database before my cart insert is executed. Or the connection might timeout. The database is MyISAM (and I can not change this, 3rd party solution).

Thank you, J

  • 写回答

1条回答 默认 最新

  • dongnao6858 2012-05-03 18:20
    关注

    I think your concern about using mysql_last_id is unfounded - it will return the last id for the current connection, not the last id globally across all connections.

    So unless you have multiple threads sharing the same database connection or you perform another identity insert on the same connection before calling mysql_last_id, you should have nothing to worry about.

    ETA: You could do this by sending multiple queries at once, like this:

    INSERT INTO ordertable VALUES(null,7,020200202,bbq);
    INSERT INTO carttable VALUES(LAST_INSERT_ID(),20120102,complete);
    

    But if you are using mysql_query it usually won't let you send multiple queries in the same call (mostly as a security measure to try to prevent SQL injection).

    评论

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上