[英]Trigger auto-incrementing composite key in MySQL
如果其他主键已经存在,只是想自动增加复合键中包含的主键之一。 Stack上的示例很少,但是以某种方式我无法使用MySQL语法获得正确的查询。 这是应该如何工作的:
operation_table:
operation_id | client_name
1 | A
1 | B
2 | A
3 | A
4 | A
2 | B
这是要实现的目标:
DELIMITER //
CREATE TRIGGER operation_id_trigger
BEFORE INSERT ON operation_table
FOR EACH ROW
BEGIN
...
END; //
非常感谢您的帮助。 它已经花了我很多时间,但我无法走得更远。
您需要的是
INSERT ... ON DUPLICATE KEY UPDATE语句
请参阅https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
当违反组合键限制时将触发此操作
建立自己的“ auto_increment”的一种方法是在触发器中有一个可以访问和更新的表。
drop table if exists t,t1;
create table t
( operation_id int, client_name varchar(1));
create table t1
(next_operation_id int,client_name varchar(1));
drop trigger if exists t;
delimiter $$
create trigger t before insert on t
for each row
begin
if exists(select 1 from t1 where t1.client_name = new.client_name) then
set new.operation_id = (select next_operation_id from t1 where t1.client_name = new.client_name);
update t1
set next_operation_id = (next_operation_id + 1)
where t1.client_name = new.client_name;
else
set new.operation_id = 1;
insert into t1 values(2,new.client_name);
end if;
end $$
delimiter ;
truncate table t;
truncate table t1;
insert into t (client_name) values
( 'A'),
( 'B'),
( 'A'),
( 'A'),
( 'A'),
( 'B');
select * from t;
+--------------+-------------+
| operation_id | client_name |
+--------------+-------------+
| 1 | A |
| 1 | B |
| 2 | A |
| 3 | A |
| 4 | A |
| 2 | B |
+--------------+-------------+
6 rows in set (0.00 sec)
select * from t1;
+-------------------+-------------+
| next_operation_id | client_name |
+-------------------+-------------+
| 5 | A |
| 3 | B |
+-------------------+-------------+
2 rows in set (0.00 sec)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.