【发布时间】:2013-05-20 01:07:31
【问题描述】:
我编写了这段代码:
INSERT into author(authorfirstname1, authorlastname1,authorfirstname2, authorlastname2)
select '".addslashes($_POST['authorfirstname1'])."','".addslashes($_POST['authorlastname1'])."','".addslashes($_POST['authorfirstname2'])."','".addslashes($_POST['authorlastname2'])."'
from author
where not exists(select authorfirstname1, authorlastname1, authorfirstname2, authorlastname2 from author
where author.authorfirstname1='".addslashes($_POST['authorfirstname1'])."'
and author.authorlastname1='".addslashes($_POST['authorlastname1'])."'
and author.authorfirstname2='".addslashes($_POST['authorfirstname2'])."'
and author.authorlastname2='".addslashes($_POST['authorlastname2'])."'
);
这段代码的重点应该是它检查数据库中是否已经存在一个值,如果不存在,则输入它。 这个 '".addslashes($_POST['authorlastname2'])."' 代表一个输入,但可以很容易地替换为 '%myentereddata%'
我的问题是它没有做任何事情......甚至没有给出错误消息,它的成功,但是如果数据库中不存在数据,它不会输入数据并且不确定如果数据存在它是否停止输入数据。
因此,如果有人可以帮助我解决此代码的问题或提供另一个示例如何以不同的方式执行此操作,我将不胜感激。
我的id是primary和serial,所以不用插入
INSERT INTO author (authorfirstname1, authorlastname1,authorfirstname2, authorlastname2)
VALUES ('one','two','three','four');
查询成功返回:1 行受影响,60 毫秒执行时间。
INSERT into author(authorfirstname1, authorlastname1,authorfirstname2, authorlastname2)
select 'one','two','three','four'
from author
where not exists(select authorfirstname1, authorlastname1, authorfirstname2, authorlastname2 from author
where author.authorfirstname1='one'
and author.authorlastname1='two'
and author.authorfirstname2='three'
and author.authorlastname2='four'
);
查询成功返回:657 行受影响,40 毫秒执行时间。
INSERT into author(authorfirstname1, authorlastname1,authorfirstname2, authorlastname2)
select 'new','new','new','new'
from author
where not exists(select authorfirstname1, authorlastname1, authorfirstname2, authorlastname2 from author
where author.authorfirstname1='new'
and author.authorlastname1='new'
and author.authorfirstname2='new'
and author.authorlastname2='new'
);
查询成功返回:1314 行受影响,70 毫秒执行时间。
【问题讨论】:
-
如果您尝试插入已经存在的行,您想得到错误吗?还是如果它不存在就插入它,如果它已经存在则安静地忽略它?
标签: postgresql sql-insert not-exists