关于插入的问题

hbgzg3006 2010-07-21 04:26:56

mytable 表机构
id,name1,name2
--我想插入的时候,如果id=1且name1=‘张三’不存在的时候才插入
insert into mytable values(1,'张三','') where?--条件如上的时候不插入
...全文
111 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
hbgzg3006 2010-07-21
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 minitoy 的回复:]

当然用merge是最好的
SQL code
SQL> SELECT * FROM test ;

A B
--- ----
14 0

SQL>
SQL> merge into test a
2 using (select 14 a,0 b from dual)b
3 on (a.a=b.a)
4 when not match……
[/Quote]
谢谢。我才知道有merge语句。
hbgzg3006 2010-07-21
  • 打赏
  • 举报
回复
各位同志们,大家好,麻烦大家试试如果id=1 and name1='',看看能不能插入。我测试能反复插入,但是如果id=1 and name='张三' 是不能反复插入的。
minitoy 2010-07-21
  • 打赏
  • 举报
回复
当然用merge是最好的
SQL> SELECT * FROM test ;

A B
--- ----
14 0

SQL>
SQL> merge into test a
2 using (select 14 a,0 b from dual)b
3 on (a.a=b.a)
4 when not matched then insert (a.a,a.b)values(b.a,b.b);

Done

SQL> select * from test;

A B
--- ----
14 0

SQL>
minitoy 2010-07-21
  • 打赏
  • 举报
回复
SQL> SELECT * FROM test ;

A B
--- ----
14 0

SQL>
SQL> INSERT INTO test
2 SELECT 14,0 FROM dual WHERE (SELECT COUNT(*) FROM test WHERE a=14)=0
3 ;

0 rows inserted

SQL>

注意是0 rows inserted
minitoy 2010-07-21
  • 打赏
  • 举报
回复
SQL> SELECT * FROM test ;

A B
--- ----
14 0

SQL>
SQL> INSERT INTO test
2 SELECT 14,0 FROM dual WHERE (SELECT COUNT(*) FROM test WHERE a=14)=0
3 ;

0 rows inserted

SQL>
hotyxm 2010-07-21
  • 打赏
  • 举报
回复

insert into mytable values(1,'张三','')
where (select 1 from mytable where id = 1 and name = '张三')=0
心中的彩虹 2010-07-21
  • 打赏
  • 举报
回复
[Quote=引用楼主 hbgzg3006 的回复:]
SQL code

mytable 表机构
id,name1,name2
--我想插入的时候,如果id=1且name1=‘张三’不存在的时候才插入
insert into mytable values(1,'张三','') where?--条件如上的时候不插入
[/Quote]

insert into mytable select 1,'张三','' from dual where (select nvl(count(1),0) from mytable where name1='张三')<=0




hbgzg3006 2010-07-21
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 minitoy 的回复:]

insert into mytable
select 1,'张三','' from dual
where (select count(*) from mytable where **='张三')=0
[/Quote]
在我这里是可以反复插入的。我的表没有主键。
yan562726884 2010-07-21
  • 打赏
  • 举报
回复
插入后面加where条件--
至于这样么。。
如果要那样的话 先从表里面查出是否存在id=1 name1='张三'的数据
没有就插入 有的话就不做
jjaihua 2010-07-21
  • 打赏
  • 举报
回复
merge into比较好
minitoy 2010-07-21
  • 打赏
  • 举报
回复
insert into mytable
select 1,'张三','' from dual
where (select count(*) from mytable where **='张三')=0
Phoenix_99 2010-07-21
  • 打赏
  • 举报
回复
建个临时表,用merge into来处理
hbgzg3006 2010-07-21
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 xinxin100198 的回复:]

做个唯一限制不就行了~~
[/Quote]
别人的表,我没办法修改
alice鑫鑫 2010-07-21
  • 打赏
  • 举报
回复
做个唯一限制不就行了~~

17,377

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧