看似微不足道
MariaDB [sandbox]> create table t(name varchar(20),age int default 0 , primary key(name));
Query OK, 0 rows affected (0.28 sec)
MariaDB [sandbox]>
MariaDB [sandbox]> INSERT INTO t (name, age)
-> VALUES
-> ('Helen', 24),
-> ('Katrina', 21),
-> ('Samia', 22),
-> ('Hui Ling', 25),
-> ('Yumie', 29)
-> ON DUPLICATE KEY UPDATE
-> age = if(VALUES(age) > age,values(age),age);
Query OK, 5 rows affected (0.03 sec)
Records: 5 Duplicates: 0 Warnings: 0
MariaDB [sandbox]>
MariaDB [sandbox]> select * from t;
+----------+------+
| name | age |
+----------+------+
| Helen | 24 |
| Hui Ling | 25 |
| Katrina | 21 |
| Samia | 22 |
| Yumie | 29 |
+----------+------+
5 rows in set (0.00 sec)
MariaDB [sandbox]>
MariaDB [sandbox]> INSERT INTO t (name, age)
-> VALUES
-> ('Helen', 25),
-> ('Katrina', 21),
-> ('Samia', 22),
-> ('Hui Ling', 25),
-> ('Yumie', 29)
-> ON DUPLICATE KEY UPDATE
-> age = if(VALUES(age) > age,values(age),age);
Query OK, 2 rows affected (0.02 sec)
Records: 5 Duplicates: 1 Warnings: 0
MariaDB [sandbox]>
MariaDB [sandbox]> select * from t;
+----------+------+
| name | age |
+----------+------+
| Helen | 25 |
| Hui Ling | 25 |
| Katrina | 21 |
| Samia | 22 |
| Yumie | 29 |
+----------+------+
5 rows in set (0.00 sec)
如果有n列在年龄变化时更新,那么
drop table if exists t;
create table t(name varchar(20),age int default 0 , col1 int, col2 int,col3 int,primary key(name));
INSERT INTO t (name, age, col1,col2,col3)
VALUES
('Helen', 24,1,1,1),
('Katrina', 21,1,1,1),
('Samia', 22,1,1,1),
('Hui Ling', 25,1,1,1),
('Yumie', 29,1,1,1)
ON DUPLICATE KEY UPDATE
col1 = if(VALUES(age) > age,values(col1),col1),
col2 = if(VALUES(age) > age,values(col2),col2),
col3 = if(VALUES(age) > age,values(col3),col3),
age = if(VALUES(age) > age,values(age),age);
select * from t;
INSERT INTO t (name, age, col1,col2,col3)
VALUES
('Helen', 25,2,2,2),
('Katrina', 21,2,2,2),
('Samia', 22,1,1,1),
('Hui Ling', 25,1,1,1),
('Yumie', 29,1,1,1)
ON DUPLICATE KEY UPDATE
col1 = if(VALUES(age) > age,values(col1),col1),
col2 = if(VALUES(age) > age,values(col2),col2),
col3 = if(VALUES(age) > age,values(col3),col3),
age = if(VALUES(age) > age,values(age),age);
select * from t;
MariaDB [sandbox]> select * from t;
+----------+------+------+------+------+
| name | age | col1 | col2 | col3 |
+----------+------+------+------+------+
| Helen | 25 | 2 | 2 | 2 |
| Hui Ling | 25 | 1 | 1 | 1 |
| Katrina | 21 | 1 | 1 | 1 |
| Samia | 22 | 1 | 1 | 1 |
| Yumie | 29 | 1 | 1 | 1 |
+----------+------+------+------+------+
5 rows in set (0.00 sec)
笔记年龄必须最后更新。没有快捷键可以键入所有可更新的列。如果年龄以外的列是动态的,那么可能值得查看动态 sql。另一种方法可能是使用触发器将插入加载到临时表中以更新主表。