我尝试插入新用户(如果用户表中不存在),我尝试了此查询但收到错误:
INSERT INTO USER (name,email)
VALUES ('John','john@mmm.com')
WHERE NOT EXISTS
(SELECT id FROM USER WHERE email = 'john@mmm.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 id from user where email = 'john@mmm.com')' at line 5
感谢,
答案 0 :(得分:7)
使用insert . . . select
:
INSERT INTO USER (name, email)
SELECT 'John', 'john@mmm.com'
WHERE NOT EXISTS
(SELECT id FROM USER WHERE email = 'john@mmm.com');
我会把它写成:
INSERT INTO USER (name, email)
SELECT name, email
FROM (SELECT 'John' as name, 'john@mmm.com' as email) t
WHERE NOT EXISTS (SELECT 1 FROM USER u WHERE u.email = t.email);
但更好的方法可能只是放入一个唯一的索引,以便数据库保护数据:
create unique index idx_users_email on user(email);
答案 1 :(得分:6)
使用INSERT ... SELECT
代替INSERT
。
INSERT INTO USER (name,email)
SELECT 'John','john@mmm.com'
WHERE NOT EXISTS
(SELECT id FROM USER WHERE email = 'john@mmm.com')
您也可以考虑使用MySQL的ON DUPLICATE KEY UPDATE
语法扩展名。