我正在使用PostgreSQL。將數據插入到通過外鍵鏈接的表中
Customer
==================
Customer_ID | Name
Order
==============================
Order_ID | Customer_ID | Price
要插入的順序,這裏是我需要平時做,
例如,「約翰」的地方「1.34」價格秩序。
(1) Get Customer_ID from Customer table, where name is "John"
(2) If there are no Customer_ID returned (There is no John), insert "John"
(3) Get Customer_ID from Customer table, where name is "John"
(4) Insert "Customer_ID" and "1.34" into Order table.
有4個SQL通信數據庫涉及這個簡單的操作!
有沒有更好的方法,使用1個SQL語句可以實現?
你可以修改你的答案,使用「RETURNING」作爲depesz建議?所以我們不需要執行額外的查詢[從customer選擇customer_id where name ='John'] – 2010-01-05 08:04:29
這不是我要做的優化。原因如下:首先,保持代碼簡單:如果第二次插入順序與第一次插入相同,則可以使用相同的代碼執行兩次插入。其次:不可能有真正的性能提升。由於您剛剛完成了對客戶的查詢,然後插入,因此Postgres將在緩存中包含該行和相應的索引,因此從客戶中選擇的內容將閃電般快速。 – 2010-01-05 14:51:21