sql通过比较值插入或更新

时间:2016-06-24 13:10:18

标签: mysql sql

假设我有一个这样的表,有很多行:

id | a | b | c

在每次INSERT之前,应该检查是否有一行具有相同的'a'和相同的'b',如果是,则不要通过总结他们的c来INSERT而是更新'c'。

如何在sql中实现?

1 个答案:

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