这是顺序解决方案(对于 postgres),当然,您必须在存储过程或应用程序代码中执行此操作。
postgres=# create table foo(id serial primary key, text varchar);
NOTICE: CREATE TABLE will create implicit sequence "foo_id_seq" for serial column "foo.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "foo_pkey" for table "foo"
CREATE TABLE
postgres=# create table bar(id int references foo, text varchar);
CREATE TABLE
postgres=# select nextval('foo_id_seq');
nextval
---------
1
(1 row)
postgres=# insert into foo values (1,'a'); insert into bar values(1,'b');
INSERT 0 1
INSERT 0 1
对于MySQL,交易很重要,不要自己绊倒,以防您将同一连接用于多个插入。
对于 LAST_INSERT_ID(),最
最近生成的 ID 保存在
服务器基于每个连接。
它不会被其他客户端更改。
如果你更新它甚至不会改变
另一个 AUTO_INCREMENT 列
非魔法值(即,一个值
不是 NULL 也不是 0)。使用
LAST_INSERT_ID() 和 AUTO_INCREMENT
同时从多个列
客户是完全有效的。每个
客户端将收到最后插入的
客户端最后一条语句的 ID
执行。
mysql> create table foo(id int primary key auto_increment, text varchar(10)) Engine=InnoDB;
Query OK, 0 rows affected (0.06 sec)
mysql> create table bar(id int references foo, text varchar(10)) Engine=InnoDB;
Query OK, 0 rows affected (0.01 sec)
mysql> begin;
Query OK, 0 rows affected (0.00 sec)
mysql> insert into foo(text) values ('x');
Query OK, 1 row affected (0.00 sec)
mysql> insert into bar values (last_insert_id(),'y');
Query OK, 1 row affected (0.00 sec)
mysql> commit;
Query OK, 0 rows affected (0.04 sec)