简体   繁体   中英

How to prevent race condition with INSERT?

How would i go about preventing race conditions when INSERTing a row into a table that contains no unique index. For example say my table is....

key | slot | label
------------------
 1  |  1   | some
 1  |  2   | some
 2  |  1   | some
 2  |  2   | some

... is the only way to prevent such race conditions to create a composite unique field such as "key:slot" eg

id  | key | slot | label
------------------------
1:1 |  1  |  1   | some
1:2 |  1  |  2   | some
2:1 |  2  |  1   | some
2:2 |  2  |  2   | some

...or is there a more efficient way that has escaped me? What about if i was to check for duplicate rows after the insert has been performed and roll the transaction back if there are any found?

actually you can do it without the key:slot column. You can define a unique compound key on the table. eg,

ALTER TABLE tableName ADD CONTRAINT tb_uq UNIQUE (`key`, slot)

插入时如何使用LOCK TABLES语法防止竞争情况?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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