How to use NOT EXISTS with COMPOSITE KEYS in SQL for inserting data from POJO

北慕城南 提交于 2019-12-08 17:34:32

问题


I am using DB2 DBMS.

Scenario 1:

myTable has a composite key (key1, key2) where both key1 and key2 are foreign keys from yourTable.

I want to insert new data from yourTable into myTable, but only if the key1, key2 combination does not already exist in myTable.

insert into myTable(key1, key2, someData)
values(x, y, z)
where NOT EXISTS (want to check if composite key is not already present)

Scenario 2:

I put data into a java object from yourTable with properties data1, data2, and data.

I want to insert the above data with the check as in Scenario1. data1 + data2 should not already be present in myTable.

How do I achieve this? I don't think we can use a SELECT statement inside the insert statement.

insert into myTable(key1, key2, data)
values(data1, data2, data)
where (data1 + data2 are already not present in myTable)

How can I achieve this?


回答1:


insert into mytable(...)
select ...
from yourtable y
left join mytable m
on y.key1 = m.key1 and y.key2 = m.key2
where m.key is null

or

insert into mytable(...)
select ...
from yourtable y
where not exists (select 1 from mytable m where y.key1 = m.key1 and y.key2 = m.key2)

for your 2nd scenario, it'd look similar to the above query

insert into mytable(...)
select ...
where not exists (select 1 from mytable m where javakey1 = m.key1 and javakey2 = m.key2)



回答2:


insert into mySchema.NIK(DATA1, DATA2, DATA) select 'C','3','MY' FROM SYSIBM.DUAL where not exists (select 1 from mySchema.NIK A where 'C' = A.DATA1 and '3' = A.DATA2)

if the data 'c' '3' already exists then above query will result in an empty table.



来源:https://stackoverflow.com/questions/7147219/how-to-use-not-exists-with-composite-keys-in-sql-for-inserting-data-from-pojo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!