我有一个人员列表及其信息,名字,姓氏,电子邮件,电话等......
无论出于何种原因,当我的同事将此列表导入数据库时,他并没有将每个人都放入其中。现在,我要让大约 500 名未能进入系统的人加入。我相信最快的方法是执行类似“如果还没有‘foobar’的电话号码,则插入此人。”
MySQL 有办法做到这一点吗?我尝试过这样做:
if not exists(Select 1 from <My Table Name> where phone = '1234567890')
Begin
<Code to insert new person>
End
但是MySQL告诉我有一个错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF not exists(SELECT 1 FROM WHERE pphone = '1234567890' at line 1
最佳答案
只需使用插入忽略
或插入重复 key 更新
。这是一个例子:
insert into <my table name>(phone, . . . )
Select '1234567890', . . .
on duplicate key update phone = phone;
on重复键更新
子句不执行任何操作,但insert
不会返回错误。
编辑:
好的,上面的方法不起作用,因为您无法声明电话号码重复。相反,您可以这样做:
insert into <my table name>(phone, . . . )
Select '1234567890', . . .
from dual
where not exists(Select 1 from <My Table Name> where phone = '1234567890');
关于mysql - 如果某个值尚未存在于 MySQL 数据库中,则插入一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23772324/