2016-08-12 78 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