【发布时间】:2020-12-08 01:58:27
【问题描述】:
为什么会出现以下错误(无法更新存储函数/触发器中的表 'table_b',因为它已被调用此存储函数/触发器的语句使用)在我尝试使用内部连接删除后出现? 我能解决吗?
DROP TABLE if exists table_b;
DROP TABLE if exists table_a;
CREATE TABLE table_a (
id int auto_increment,
name varchar(255) DEFAULT NULL,
primary key (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
DROP TABLE if exists table_b;
CREATE TABLE table_b (
id int auto_increment,
name varchar(255) DEFAULT NULL,
id_table_a int NOT null,
another_table_id int NOT null,
foreign key (id_table_a) references table_a(id),
primary key (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
DELIMITER $$
drop trigger if exists tg_test$$
create trigger tg_test before delete on table_a for each row
begin
delete from table_b where id_table_a = OLD.id;
end$$
DELIMITER ;
insert into table_a(name) values('t-a');
insert into table_b(name, id_table_a, another_table_id) values('t-b', 1, 23);
-- Error Can't update table 'table_b' in stored function/trigger because it is already used by statement which invoked this stored function/trigger
-- in any of this two lines
delete table_a from table_a inner join table_b on table_b.id_table_a = table_a.id where another_table_id = 23;
delete from table_a where id in (select id_table_a from table_b where another_table_id = 23);
-- Success
delete from table_a where id = 1;
【问题讨论】:
-
我可以只使用 another_table_id 23 删除 table_a 吗?
标签: mysql sql triggers subquery sql-delete