Consider we have a table t_log
in database Test
. The t_log looks like the following
create table `t_log`(
`F_log_id` bigint(20) not null AUTO_INCREMENT,
`F_trans_id` bigint(20) not null,
`F_action` tinyint(3) not null,
primariy key(`F_log_id`)
)engine=innodb
Suppose F_action
field can only take several specific values,like 1 and 2. For F_action
=1 records, coresponding F_trans_id
must differ from each other. While for F_action
=2 records, coresponding F_trans_id
can take same values.
For example records like the following in table should be valid
F_log_id | F_action | F_trans_id
1 1 1001
2 2 1002
3 2 1002
However records like the following should not be valid
F_log_id | F_action | F_trans_id
1 1 1001
2 1 1001
3 2 1002
Since our unique restriction on F_trans_id
depends on the specific value of F_action
, we cannot merely build the unique index on F_trans_id and F_action.
For consistency, inserting records into t_log is put into a transaction like this
start_transaction()
select and check if valid
do inserting
commit()
However in high-concurrency environment, there might be two inserting transaction arrived almost at the same time, for example, both entered start_transaction(), suppose two records are both (F_action=1, F_trans_id=222), when select and check, both found record is valid and insert it. Then t_log
will have invalid two records.
Is there any good way two prevent this kind of invalid records? Thank you.