永发信息网

SQL 当记录不存在时插入insert if not exists

答案:6  悬赏:80  手机版
解决时间 2021-02-16 06:11
  • 提问者网友:佞臣
  • 2021-02-15 05:54
SQL 当记录不存在时插入insert if not exists
最佳答案
  • 五星知识达人网友:有你哪都是故乡
  • 2021-02-15 06:18
表是空的当然添加不了数据,因为exists存在谓词返回的是布尔值TRUE和FALSE,你的select * from clientswhere id = 10345 是空值;那么WHERe not exists (select * from clientswhere id = 10345)的意思是限定条件 WHERe 不存在空值,但是事实上表里此时正是空,所以查询不符合WHERe条件,所以insert 也是空,就没记录了。

还有,你的语句
INSERT INTO clients(id, name, type)SELECT 10345, 'IBM', 'advertising'…
select 后面跟的不是字段名,而是值,为什么还要用INSERT INTO…SELECT ?
直接insert into…values(…)不就好了?
全部回答
  • 1楼网友:枭雄戏美人
  • 2021-02-15 11:06
这样写肯定是不对的。
  • 2楼网友:千夜
  • 2021-02-15 09:41
WHERe not exists (select * from clients
where id = 10345); 我觉得where not exists这有问题吧?exists是个栏位?后面怎么是select * from 呢?应该是指定一个栏位,WHERe not exists (select exists from clients where id = 10345)
  • 3楼网友:神也偏爱
  • 2021-02-15 08:51
因为表中没有数据,
insert into clients
select ...
FROM clients
当然没有数据返回,insert自然也就没有数据可以插入了。
这个好像必须用程度段,纯粹的sql语句还真实现不了
  • 4楼网友:神的生死簿
  • 2021-02-15 08:35
sql导出建表语句的sql文件你看过吗?前面就是判断表是否存在,然后建表
就是那些if not exists 之类的,你照着改一下就行了,手头没有sql,没办法给你贴语句
  • 5楼网友:等灯
  • 2021-02-15 07:43
INSERT INTO clients
SELECt 10345, 'IBM', 'advertising'
FROM dual
WHERe not exists (select * from clients
where id = 10345);

这个可以实现
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯