java - 如何在 SQL 中使用 NOT EXISTS 和 COMPOSITE KEYS 从 POJO 插入数据

标签 java sql database db2 composite-key

我正在使用 DB2 数据库管理系统。

场景 1:

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

我想将新数据从 yourTable 插入到 myTable,但前提是 myTable 中不存在 key1、key2 组合。

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

场景 2:

我将数据从 yourTable 放入一个具有属性 data1、data2 和 data 的 java 对象中。

我想像场景 1 一样插入上面的数据和支票。 data1 + data2 不应已存在于 myTable 中。

我如何实现这一目标?我不认为我们可以在插入语句中使用 SELECT 语句。

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

我怎样才能做到这一点?

最佳答案

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

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)

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

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

关于java - 如何在 SQL 中使用 NOT EXISTS 和 COMPOSITE KEYS 从 POJO 插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7147219/

相关文章:

double 上的Java正则表达式

java - 在某些情况下处理 RuntimeExceptions 有效吗?

sql - 在 SQL 中引用计算值

database - 在 oracle 中停止执行 sqlplus 错误的批处理文件

java - 更改Java中导入的名称,或者导入两个同名的类

java - Selenium 多次点击

sql - SQL Server 2005 中 VARBINARY 字段的大小

php - 乘以货币兑换列

database - 我应该混淆用户的数据库 ID 吗?

database - 在 REST API 中的何处存储资源 URI