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


mysql insert into two tables using auto_increment value from the first table as a foreign key in the second

>我想插入购物车表

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

使用订单表中的自动递增值 orderId

**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)

但随后使用 orderId(现在是 5)

INSERT INTO carttable VALUES(orderId,20120102,complete)

然而此插入必须作为同一查询完成。如果我使用 mysql_last_id (php),则在我的购物车插入执行之前,其他人有机会插入数据库。否则连接可能会超时。数据库是MyISAM(我无法更改此,第三方解决方案)。

谢谢J

我认为您对使用 mysql_last_id 的担忧是没有根据的 - 它将返回当前连接的最后一个 id,而不是所有连接中的全局最后一个 id。

因此,除非您有多个线程共享同一个数据库连接,或者在调用mysql_last_id之前在同一连接上执行另一个身份插入,否则您应该没有什么可担心的。

ETA:您可以通过一次发送多个查询来做到这一点,如下所示:

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

但是如果你使用mysql_query它通常不会让你在同一次调用中发送多个查询(主要是作为一种安全措施来试图防止SQL注入)。