正如评论中提到的和随后请求的那样 - trigger 似乎是解决问题的好选择,因为您只需要关心初始插入 - 然后重复的 ID(或其他字段)由自动处理触发器。
给定两个基本表来复制问题中的这些
mysql> describe employees;
+----------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | 0 | |
| position | varchar(50) | NO | | 0 | |
| salary | decimal(10,2) | NO | | 0.00 | |
+----------+------------------+------+-----+---------+----------------+
mysql> describe date;
+-----------+------------------+------+-----+-------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+------------------+------+-----+-------------------+-------+
| id | int(10) unsigned | NO | PRI | NULL | |
| timestamp | timestamp | NO | | CURRENT_TIMESTAMP | |
+-----------+------------------+------+-----+-------------------+-------+
一个简单的trigger 绑定到employees 表并在添加新行时插入到date 表中。
CREATE TRIGGER `tr_employee_inserts` AFTER INSERT ON `employees` FOR EACH ROW BEGIN
insert into `date` set `id`=new.id;
END
测试
insert into employees (`name`,`position`,`salary` ) values ( 'Peter', 'Porcupine Pickler', 75000 );
insert into employees (`name`,`position`,`salary` ) values ( 'Roger', 'Rabitt Rustler', 25000 );
insert into employees (`name`,`position`,`salary` ) values ( 'Michael', 'Mouse Mauler', 15000 );
select * from `employees`;
select * from `date`;
结果
mysql> select * from employees;
+----+---------+-------------------+----------+
| id | name | position | salary |
+----+---------+-------------------+----------+
| 1 | Peter | Porcupine Pickler | 75000.00 |
| 2 | Roger | Rabitt Rustler | 25000.00 |
| 3 | Michael | Mouse Mauler | 15000.00 |
+----+---------+-------------------+----------+
mysql> select * from date;
+----+---------------------+
| id | timestamp |
+----+---------------------+
| 1 | 2020-01-16 10:11:15 |
| 2 | 2020-01-16 10:11:15 |
| 3 | 2020-01-16 10:11:15 |
+----+---------------------+