2015-05-21 21 views
0

只有當表中不存在該行的列時,才能將行插入表中的最佳方式是什麼。kdb +條件插入:僅在列值不存在時插入

例如爲:

q)table:([] col1:(); col2:(); col3:()); 
q)`table insert (1;2;3); 
q)conditionalInsert:{if[first where table.col1=x(0)~0N;`table insert x]}; 

現在在做的時候以下幾點:

q)conditionalInsert[(1;2;3)]; 
q)conditionalInsert[(7;8;9)]; 

結果產生:

q)table 
col1 col2 col3 
-------------- 
1 2 3 
7 8 9 

這或許可以更容易地完成。我的問題:什麼是最簡單/最好的方法?

要清楚:列可能是非鍵控的列。

或者換句話說:表要麼鍵控或非鍵控和目標列不是鍵(或部分的化合物鍵列)

回答

1

首先就是在目標列上有適當的屬性(排序,組),這將使功能更快。

現在有2種情況,我能想到的:

一)表是方向性的,目標列是鍵列:在這種情況下,正常的插會像你的條件插入的方式工作。

b)中表或者是鍵合或非鍵控和目標列不是鍵(或部分的化合物鍵列):

  q)conditionalInsert: {if[not x[0] in table.col1;`table insert x]} 

其更好地使用「EXEC」代替' table.col1'作爲點符號不適用於鍵控表:

  q)conditionalInsert: {if[not x[0] in exec col1 from table;`table insert x]} 
+0

情景b的確如此。我更新了我的問題。沒有比創建函數更簡單/更簡單的方法嗎? –

+0

你在問KDB是否提供了任何內置函數來做到這一點,我不這麼認爲。即使存在,它也會在後端做同樣的事情,或者暫時將該列作爲主鍵並插入。 – Rahul

+0

也許你是對的。我會保持打開一段時間,看看是否有其他答案出現。 –

2

使用一個密鑰表?

q)table 
col1| col2 col3 
----| --------- 
1 | 2 3 
q)`table insert (1;2;4) 
'insert 
q)`table insert (2;2;4) 
,1 
q)table 
col1| col2 col3 
----| --------- 
1 | 2 3 
2 | 2 4 

您可以隨時使用受保護的評估來消除錯誤。

q).[insert;(`table;(1;2;4));{`already_there}] 
`already_there 
q).[insert;(`table;(3;2;4));{`already_there}] 
,2 
q)table 
col1| col2 col3 
----| --------- 
1 | 2 3 
2 | 2 4 
3 | 2 4 
+0

這確實是鍵控列的最佳答案,但我也希望爲非鍵控表找到一個乾淨的解決方案。 –