在插入新数据之前截断 table

Truncate table before inserting new data

我试图在插入一组新数据之前清除/清空/截断 MySQL 中的 table。我认为这只能使用触发器来完成。

我创建了以下触发器:

create trigger top_destinations_truncate BEFORE INSERT
on top_destinations FOR EACH ROW
delete from top_destinations

但是当我尝试在我的查询中添加几百条记录时,我得到了这个错误:

HY000Can't update table 'top_destinations' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

如果触发器不存在,insert into table top_destinations 查询本身可以正常工作。但我每次都需要重新开始...

我能做什么?也许在 MySQL 中有更好的方法,无需触发器:就像顺序查询一样。首先截断,稍等片刻,然后插入(如果可能)。

您可以使用 TRANSACTION,因此您的 Table 对于其他查询永远不会为空,但这不是最快的方法。

START TRANSACTION;
DELETE FROM your_table;
INSERT into your_table ...
...
INSERT into your_table ....
COMMIT;

或更快的方式:

TRUNCATE yout_table;
INSERT into your_table ...
...
INSERT into your_table ....

以这种方式,TRUNCATE 删除并重新创建 table 并且不能在 TRANSACTION 中使用,但速度非常快。