MySQL查询仅在两个字段不存在时插入数据

时间:2017-05-12 11:45:51

标签: jquery mysql insert

我有学生表,如果表格中不存在电子邮件和电话号码,我想插入数据。我试过这个查询,

INSERT INTO studesnts (name, phone, email, address) 
  VALUES ('vinod','9999999999','xyz@example.com','my address') 
  WHERE NOT EXISTS (SELECT * FROM studesnts WHERE phone ='9999999999' AND email='xyz@example.com')

但是此查询返回错误

 #1064 - 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 'WHERE NOT EXISTS (SELECT * FROM studesnts ( WHERE phone ='9999999999' ' at line 2

如何解决此问题?

1 个答案:

答案 0 :(得分:4)

VALUES不接受WHERE条款。您可以改为使用SELECT

INSERT INTO students (name, phone, email, address) 
    SELECT s.*
    FROM (SELECT 'vinod' as name, '9999999999' as phone, 'xyz@example.com' as email, 'my address' as address) s
    WHERE NOT EXISTS (SELECT 1
                      FROM students s2
                      WHERE s2.phone = s.phone AND s2.email = s.email
                     );

但是,您可能打算避免在表格中使用相同手机和电子邮件的学生。如果是,请创建唯一约束或索引:

create unique index unq_students_phone_email on students(phone, email);

这样,数据库可以保证数据的完整性。在正常情况下会导致错误。如果您只想忽略重复插入,则可以执行以下操作:

INSERT INTO students (name, phone, email, address) 
    VALUES ('vinod', '9999999999', 'xyz@example.com', 'my address') 
    ON DUPLICATE KEY UPDATE phone = VALUES(phone);

在重复的情况下,这是一个无操作。