我正在尝试仅在新客户端尚不存在的情况下插入新客户端。我在使用SQL语句时遇到了问题,但我也希望在PHP中提供上下文:
$sql = "INSERT INTO clients
(`studentEmail`, `studentPassword`, `parentEmail`, `parentPassword`,
`studentFirstName`, `studentLastName`, `studentPhone`, `parentFirstName`,
`parentLastName`, `parentPhone`, `school`)
VALUES ('$studentEmail', '$studentPassword', '$parentEmail',
'$parentPassword', '$studentFirstName', '$studentLastName',
'$studentPhone', '$parentFirstName', '$parentLastName', '$parentPhone', '$school')
SELECT studentEmail
FROM clients
WHERE not exists (select * from clients where studentEmail == '"$studentEmail"')";
答案 0 :(得分:3)
在插入语句中,select
和values
是互斥的。而不是:
insert table1 (col1, col2, col3, ...)
values (1, 2, 3, ...)
select col1
where not exists (...)
尝试:
insert table1 (col1, col2, col3, ...)
select 1, 2, 3, ...
where not exists (...)
答案 1 :(得分:2)
在插入数据之前,您应该检查电子邮件是否存在。
$check = mysql_query("SELECT studentEmail FROM clients WHERE studentEmail = '{$studentEmail}';");
if (mysql_num_rows($check) == 0) {
// insert
}
答案 2 :(得分:0)
您可以使用MERGE
声明:
merge into clients on (select 1 from clients where studentEmail = blabla)
when not matched then insert blabla
(合并语句的语法会因您的RDBMS而异,请查看特定RDBMS实现的文档)
答案 3 :(得分:0)
如果您在电子邮件字段中有唯一索引,那么您只需执行INSERT IGNORE ...
即可轻松放弃与现有电子邮件相对应的插入内容。