如果数据与其他匹配,如何在表中更新数据然后插入mysql

时间:2019-05-28 05:18:01

标签: mysql

如果有匹配项,则在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 | 
+----+--------+-----------------+

2 个答案:

答案 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"