简体   繁体   English

事务期间不会阻止SQL UPDATE / INSERTS

[英]SQL UPDATES/INSERTS are not getting blocked during a transaction

I have a table where it is constantly being sent UPDATES/INSERTS from other processes, and I am trying to perform a transaction to my SQL table where I rotate the table and move some of the last values into the new table that I just created: 我有一个表,该表不断从其他进程发送更新/插入,并且正在尝试对我的SQL表执行事务,在该表中我旋转表并将一些最后的值移到刚创建的新表中:

BEGIN TRANSACTION;
CREATE TABLE temp LIKE sales;
RENAME TABLE sales TO sales_05_04_19, temp TO sales
INSERT INTO sales SELECT * FROM sales_05_04_19 WHERE time > 1556953200000;
COMMIT;

But it does not appear to be blocking these UPDATES/INSERTS and some seem to actually make it through to the newly created sales table before the transaction's INSERT occurs. 但是它似乎并没有阻止这些UPDATES / INSERTS,并且似乎确实可以在事务的INSERT发生之前将其直通到新创建的sales表。 This causes me to get the error on the transaction insert: 这使我在事务插入上得到错误:

(1062, "Duplicate entry '1' for key 'PRIMARY'")

I thought that this transaction would block the UPDATES/INSERTS until it commits, but that doesn't seem to be the case here. 我认为该事务将阻止UPDATES / INSERTS,直到它提交为止,但在这里似乎并非如此。 So I feel that I would need to acquire a lock. 所以我觉得我需要获得一把锁。 How would I go about doing this (if that is the right approach to fixing this)? 我将如何去做(如果这是解决此问题的正确方法)?

If you want to prevent updates on a table while you do this kind of thing, you'll need to LOCK TABLES rather than use a transaction. 如果您想在执行此类操作时防止在表上进行更新,则需要锁定表而不是使用事务。 I suggest creating your new table, locking both it and the old one, doing the rename switcheroo, doing your insert, then releasing the locks. 我建议创建新表,将其与旧表锁定,进行重命名switcheroo,进行插入,然后释放锁。 There is no need for the transaction. 无需进行交易。 Transactions avoid inconsistency, but they do not guarantee order, and DDL statements like create and rename table are not transaction-safe in any case. 事务避免不一致,但是它们不能保证顺序,并且在任何情况下,诸如create和named表之类的DDL语句都不安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM