假设我有一个这样的表,有很多行:
id | a | b | c
在每次INSERT之前,应该检查是否有一行具有相同的'a'和相同的'b',如果是,则不要通过总结他们的c来INSERT而是更新'c'。
如何在sql中实现?
答案 0 :(得分:6)
这是 ON DUPLICATE KEY 的示例:
您必须在a和b
上创建唯一键ALTER TABLE my_table 添加UNIQUE KEY idx_ab(a,b);
插入或更新
INSERT INTO my_table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE c=c+VALUES(c);
<强>样品强>
MariaDB [yourSchema]> select * from my_table;
Empty set (0.00 sec)
MariaDB [yourSchema]> INSERT INTO my_table (a,b,c) VALUES (1,2,3),(4,5,6) ON DUPLICATE KEY UPDATE c=VALUES(c);
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
MariaDB [yourSchema]> select * from my_table;
+----+------+------+------+
| id | a | b | c |
+----+------+------+------+
| 6 | 1 | 2 | 3 |
| 7 | 4 | 5 | 6 |
+----+------+------+------+
2 rows in set (0.00 sec)
MariaDB [yourSchema]> INSERT INTO my_table (a,b,c) VALUES (1,2,99) ON DUPLICATE KEY UPDATE c=VALUES(c);
Query OK, 2 rows affected (0.05 sec)
MariaDB [yourSchema]> select * from my_table;
+----+------+------+------+
| id | a | b | c |
+----+------+------+------+
| 6 | 1 | 2 | 99 |
| 7 | 4 | 5 | 6 |
+----+------+------+------+
2 rows in set (0.00 sec)
MariaDB [yourSchema]>