只有在表中不存在该行的列时,将行插入表中的最佳方法是什么。
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
这可能更容易实现。我的问题:最简单/最好的方法是什么?
需要明确的是:该列可能是非键控列。
或者换句话说:表是键控的或非键控的,目标列不是键(或复合键列的一部分)
首先要在目标列上具有适当的属性(排序,分组),这将使功能更快。
现在我可以想到两种情况:
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]}
使用键控表?
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