2016-08-12 77 views
0

相同的结果我试图将数据插入到两个表,其中表2没有主键,但只有外国的:选择最后一个ID返回多个请求

insert into table1 ....; 
insert into table2 (a, column2, c) values(1, (select id from table1 order by inserted_at desc limit 1), 33); 

insert into table1 ....; 
insert into table2 (a, column2, c) values(1, (select id from table1 order by inserted_at desc limit 1), 33); 

insert into table1 ....; 
insert into table2 (a, column2, c) values(1, (select id from table1 order by inserted_at desc limit 1), 33); 

和我结束了同一个ID中所有3个请求中的table2column2。为什么以及我该如何修复?

+0

你确定你在所有3次迭代中都不在'table1'中插入类似的数据?很难理解,除非你提供了'table1'的精确插入语句,并解释了如何使用'inserted_at'。我猜你在插入sysdate,但没有插入语句,我们只能猜测。 – Utsav

+0

使用串行列。不要自己计算ID - 数据库会为你做这件事。 –

+0

@戈登林诺夫,我没有。 – Johshi

回答

0

,因为你在一个事务乳宁3插入

你应该添加的每个befere插入start transaction; 每个后插入commit;

+1

不确定这是否正确。在一个事务中值应该是可见的。 OP最有可能使用系统日期,所有插入的值都相同,但只有在问题中发布完整详细信息时才能确认。 – Neeraj

+0

@Neeraj:如果'inserted_at'基于默认的'now()',它将在事务开始的时间戳被冻结。 – joop

1

考虑这样做,而不是:

INSERT INTO table2 (a, column2, c) VALUS(1, (INSERT INTO table1 ... RETURNING id), 33); 
+0

这是整洁。是否有可能在纯sql的instuctions中声明一个变量,就像我的问题一样,并用它来保存从“insert into table1”返回的id? – Johshi

+0

变量声明来自PLSQL。 – emacsx

+0

是否有可能在纯sql的instuctions中声明一个变量,就像我的问题一样,并用它来保存从“insert into table1”返回的id? – Johshi