我觉得这应该很简单,但是我在寻找最佳方法方面遇到了问题
此subitem_to_item_status表中有许多具有状态的子项,但是我需要为所有尚未存在的子项插入一条记录。我不需要更新其中的内容,我实际上只是在尝试复制“插入/忽略”
子项目的样本数据
ITEM_SUBITEMT
item_subitem_id | creator_identifier
-----------------------------------------
12 12345
13 12345
14 12345
15 12345
16 12345
17 12345
18 12345
19 12345
20 12345
21 12345
22 12345
SUBITEM_TO_ITEM_STATUS
SUBITEM_ID | ITEM_STATUS_ID | CREATED_BY_IDENTIFIER
------------------------------------------------------------
12 1 12345
15 1 12345
16 1 12345
20 1 12345
所以有了这些数据,我只需要插入第一个表中没有ID 12,15,16或20的记录
MERGE INTO schema.SUBITEM_TO_ITEM_STATUS (SUBITEM_ID,ITEM_STATUS_ID, CREATED_BY_IDENTIFIER,ROWCHANGE,CREATED_AT) AS T
USING( (SELECT ITEM_SUBITEM_ID, 1, CREATOR_IDENTIFIER, NOW(),NOW() FROM schema.ITEM_SUBITEMT) AS S
ON S.ITEM_SUBITEM_ID = T.SUBITEM_ID
WHEN NOT MATCHED THEN INSERT;
答案 0 :(得分:1)
错误的MERGE
语句。
试试这个:
MERGE INTO schema.SUBITEM_TO_ITEM_STATUS T
USING (SELECT ITEM_SUBITEM_ID, 1 AS ITEM_STATUS_ID, creator_identifier FROM schema.ITEM_SUBITEMT) S ON S.ITEM_SUBITEM_ID = T.SUBITEM_ID
WHEN NOT MATCHED THEN
INSERT (SUBITEM_ID, ITEM_STATUS_ID, CREATED_BY_IDENTIFIER)
VALUES (S.item_subitem_id, S.ITEM_STATUS_ID, S.creator_identifier);
答案 1 :(得分:0)
为什么不使用insert
?
insert into SUBITEM_TO_ITEM_STATUS (SUBITEM_ID, ITEM_STATUS_ID, CREATED_BY_IDENTIFIER)
select item_subitem_id, 1, creator_identifier
from ITEM_SUBITEMT
where item_subitem_id not in (12, 15, 16, 20);
如果您的意思是不想在表中重复,则可以尝试:
insert into SUBITEM_TO_ITEM_STATUS (SUBITEM_ID, ITEM_STATUS_ID, CREATED_BY_IDENTIFIER)
select item_subitem_id, 1, creator_identifier
from ITEM_SUBITEMT s
where not exists (select 1
from SUBITEM_TO_ITEM_STATUS tis
where tis.item_subitem_id = s.item_subitem_id
);