2013-03-22 92 views
0

嗨我正在嘗試在postgreSql表中執行以下操作,但遇到語法問題。PostgreSQL如果表A不包含值,則插入到表A和表B中

僞代碼:

if (tableA.column1 does not contain value1) 
{ 
    INSERT INTO tableA (column1, column2) 
    VALUES value1, value2 
} 

// do this check even if the above already existed 
if (tableB does not contain value1 and value3 in the same row) 
{ 
    // it is ok if value1 and value3 already exist in the table, just not the same row 
    INSERT INTO tableB (column1, column2) 
    VALUES (value1, value3) 
} 

return true 

與此操作的實際語法任何幫助,將不勝感激!

+0

我不明白第一個和第二個條件是如何「歸屬」在一起的。你可以簡單地運行兩個彼此獨立。 – 2013-03-22 14:12:49

+0

有趣,現在我看着它,你說得很好! – dcoffey3296 2013-03-22 14:16:55

回答

2
-- first insert: 
insert into tablea (col1, col2) 
select 1,2 
from tablea 
where not exists (select * from tablea where col1 = 1); 

-- second insert (same logic to apply a conditional insert) 
insert into tableb (col1, col2) 
select 1,2 
from tableb 
where not exists (select * from tableb where col1 = 1 and col2 = 2); 
+1

只要記住'LOCK'表或準備處理錯誤(如果唯一)或重複(如果不是唯一的)由於多個交易同時檢查並插入相同的記錄。 – 2013-03-22 14:22:36

+0

@CraigRinger:爲什麼鎖定?是不是簡單地包裝到一個交易足夠? – mvp 2013-03-23 08:03:17

+0

@mvp如果你知道沒有其他人會同時插入,是的。但是如果你知道你知道它不會花費任何東西來鎖定。插入不會彼此阻塞。如果在兩個併發插入之間共享一個唯一的鍵,那麼*兩個*都將會是「SELECT」,並且看不到鍵,則兩者都會嘗試插入它。一個會贏,另一個將無法承擔重複鍵錯誤,儘管無法看到衝突的行。如果*不是*唯一鍵,那麼可見性規則將導致無法看到另一個正在插入的行以及兩行被插入。 – 2013-03-23 11:27:49