kdb +条件插入:仅在列值不存在时插入

问题描述 投票:1回答:2

只有在表中不存在该行的列时,将行插入表中的最佳方法是什么。

Ef。:

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

这可能更容易实现。我的问题:最简单/最好的方法是什么?

需要明确的是:该列可能是非键控列。

或者换句话说:表是键控的或非键控的,目标列不是键(或复合键列的一部分)

insert-update kdb
2个回答
2
投票

首先要在目标列上具有适当的属性(排序,分组),这将使功能更快。

现在我可以想到两种情况:

a)表是键控的,目标列是键控列:在这种情况下,正常插入将像条件插入一样工作。

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]}  

3
投票

使用键控表?

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  
© www.soinside.com 2019 - 2024. All rights reserved.