鍍金池/ 問答/數(shù)據(jù)庫/ mysql 如何在添加約束鍵后,再添加相同的行時使其某字段相加,而不是報錯

mysql 如何在添加約束鍵后,再添加相同的行時使其某字段相加,而不是報錯

mysql test1@127.0.0.1:test> alter table test add constraint uk_test unique (a,b);
Query OK, 0 rows affected
Time: 0.090s
mysql test1@127.0.0.1:test> insert into test (a,b,c) values ('1','2','3');
Query OK, 1 row affected
Time: 0.004s
mysql test1@127.0.0.1:test> select * from test;
+---+---+---+
| a | b | c |
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
1 row in set
Time: 0.012s
mysql test1@127.0.0.1:test>

在設置約束鍵后,當我在 insert 一條相同的數(shù)據(jù)時,我想 new.c + old.c;

#當我添加一條相同的數(shù)據(jù)時;

mysql test1@127.0.0.1:test> insert into test (a,b,c) values ('1','2','3');
Query OK, 1 row affected
Time: 0.004s

#正常情況會報錯,但我想要得到下面的效果 c = (new.c + old.c);


mysql test1@127.0.0.1:test> select * from test;
+---+---+---+
| a | b | c |
+---+---+---+
| 1 | 2 | 6 | 
+---+---+---+
1 row in set
Time: 0.012s

有這種操作嗎?

#或者可以這樣嗎:

alter table test add constraint uk_test unique (a,b) on add sum(c);
回答
編輯回答
瘋子范
create unique index uk_abc on tt(a,b,c);
INSERT INTO tt (a,b,c) VALUES (1,2,3) 
  ON DUPLICATE KEY UPDATE c=c+values(c);
2017年9月22日 04:01