如果有匹配项,则在sql中插入一行,然后对其进行更新。
我尝试过
INSERT INTO test (name, email)
SELECT * FROM (SELECT 'Rupert', 'Somewhere@s.com') AS tmp
WHERE NOT EXISTS (
SELECT name FROM test WHERE name = 'Rupert'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `test`;
+----+--------+-----------------+
| id | name | email |
+----+--------+-----------------+
| 1 | Rupert | Somewhere@s.com |
+----+--------+-----------------+
这仅适用于检查重复项。但是我想如果没有发现问题,请插入它,而不是对其进行更新。
INSERT INTO test (name, email)
SELECT * FROM (SELECT 'Rupert', 'Somewhere@somewhere.com') AS tmp
WHERE NOT EXISTS (
SELECT name FROM test WHERE name = 'Rupert'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `test`;
+----+--------+-----------------+
| id | name | email |
+----+--------+-----------------+
| 1 | Rupert | Somewhere@s.com |
+----+--------+-----------------+
答案 0 :(得分:1)
您可以使用ON DUPLICATE KEY
首先,您必须创建唯一索引:
ALTER TABLE
测试ADD UNIQUE email(
电子邮件`);
因此,如果您插入具有相同电子邮件值的记录,它将更新该记录。
INSERT INTO test (name, email) VALUES("Rupert", "Somewhere@s.com")
ON DUPLICATE KEY UPDATE name="Rupert", email="Somewhere@s.com"
如果是新电子邮件,它将创建新记录
答案 1 :(得分:0)
首先,您需要运行此查询
ALTER TABLE test ADD CONSTRAINT email UNIQUE (email);
之后然后使用它会更新您的记录(如果存在)
INSERT INTO test (name,email) VALUES ('Gorilla','Somewhere@s.com') ON DUPLICATE KEY UPDATE email = "Somewhere@somewhere.com"