如何在SQL中使用NOT EXISTS与COMPOSITE KEYS来插入POJO中的数据 [英] How to use NOT EXISTS with COMPOSITE KEYS in SQL for inserting data from POJO

查看:158
本文介绍了如何在SQL中使用NOT EXISTS与COMPOSITE KEYS来插入POJO中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用DB2 DBMS。



情景1:



myTable有一个复合键(key1,key2),其中key1和key2都是来自yourTable的外键。



我想将新数据从yourTable插入myTable,但只有当key1,key2组合在myTable中不存在。

 插入myTable(key1,key2,someData)
值(x,y,z)
其中NOT EXISTS(想检查复合键是否还没有存在)

方案2:



我将数据从yourTable中的数据放入属性data1,data2和data中。 p>

我想使用方案1中的支票插入上述数据。 data1 + data2不应该已经存在于myTable中。



我该如何实现?我不认为我们可以在insert语句中使用SELECT语句。

  insert into myTable(key1,key2,data) 
值(data1,data2,data)
其中(data1 + data2已经不存在于myTable中)

如何实现这一点?

解决方案

  insert into mytable (...)
select ...
from yourtable y
left join mytable m
on y.key1 = m.key1 and y.key2 = m.key2
其中m.key为空

  insert into mytable(...)
select ...
from yourtable y
其中不存在(从mytable m中选择1,其中y .key1 = m.key1和y.key2 = m.key2)

为您的第二种情况,它'看起来类似于上述查询

  insert into mytable(...)
select ...
其中不存在(从mytable m中选择1,其中javakey1 = m.key1和javakey2 = m.key2)


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?

解决方案

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)

这篇关于如何在SQL中使用NOT EXISTS与COMPOSITE KEYS来插入POJO中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆