Sql Oracle-在不存在的位置插入select max

Sql Oracle-在不存在的位置插入select max,sql,oracle,Sql,Oracle,我正试着写下面这样的东西 目标是不要有多个具有相同描述的记录。我们对description列有唯一的约束 我必须编写这个insert查询,即使它被意外执行了不止一次,它也应该能够工作(不会抛出错误)。列id是表的主键 insert into test (id, description) select max(id)+1, 'test record' from test where not exists ( select 1 from test where description = 'test

我正试着写下面这样的东西

目标是不要有多个具有相同描述的记录。我们对description列有唯一的约束

我必须编写这个insert查询,即使它被意外执行了不止一次,它也应该能够工作(不会抛出错误)。列id是表的主键

insert into test (id, description)
select max(id)+1, 'test record' from test
where not exists ( select 1 from test where description = 'test record' );
如果测试表中已有一条description='testrecord'的记录,则以下查询的结果id为null,插入失败,主键冲突

select max(id)+1, 'test record' from test
where not exists ( select 1 from test where description = 'test record' );
如果我必须交替地用变量和begin/end编写sql块来完成这项工作,我很乐意这样做
但是,任何建议都值得赞赏

将select语句嵌套在另一个查询中,如下所示:

insert into test (id, description)
select t.id, t.description
from (
  select max(id)+1 as id, 'test record' as description
  from test
  where not exists (select 1 from test where description = 'test record' )
) t
where t.id is not null

请参见。

将select语句嵌套在另一个查询中,如下所示:

insert into test (id, description)
select t.id, t.description
from (
  select max(id)+1 as id, 'test record' as description
  from test
  where not exists (select 1 from test where description = 'test record' )
) t
where t.id is not null

请参阅。

在没有
group by
子句的情况下使用聚合函数会强制查询生成记录,即使
where
子句删除了所有行

快速解决方法是添加(虚拟)
groupby
子句:

insert into test (id, description)
select max(id)+1, 'test record' from test
where not exists ( select 1 from test where description = 'test record' )
group by 2;
或者,也可以将聚合函数移动到子查询。我发现该解决方案使意图更加明确:

insert into test (id, description)
select t.id, 'test record' 
from (select max(id) + 1  id from test) t
where not exists ( select 1 from test where description = 'test record');

在没有
group by
子句的情况下使用聚合函数会强制查询生成记录,即使
where
子句删除了所有行

快速解决方法是添加(虚拟)
groupby
子句:

insert into test (id, description)
select max(id)+1, 'test record' from test
where not exists ( select 1 from test where description = 'test record' )
group by 2;
或者,也可以将聚合函数移动到子查询。我发现该解决方案使意图更加明确:

insert into test (id, description)
select t.id, 'test record' 
from (select max(id) + 1  id from test) t
where not exists ( select 1 from test where description = 'test record');

因此,如果表中已存在描述为“测试记录”的记录,是否要插入新记录?抱歉,不清楚;如果描述为“test record”的记录已经存在,我们不希望插入,也不希望抛出错误。由于
id
是主键,如果同时执行,将导致错误。为什么不使用序列来生成
ID
?因此,如果表中已经存在描述为
的“测试记录”
的记录,是否要插入新记录?抱歉,不清楚;如果描述为“test record”的记录已经存在,我们不希望插入,也不希望抛出错误。由于
id
是主键,如果同时执行,将导致错误。为什么不使用序列来生成
ID