如何在mysql中实现多个NULL检查事务

时间:2016-07-11 05:32:58

标签: mysql sql database isolation-level transaction-isolation

我想在MYSQL中实现NULL检查逻辑。这是代码:

mysql> create table temp
(
id int,
des varchar(100),
primary key (id)
);

mysql> SELECT @@tx_isolation;
+-----------------+
| @@tx_isolation  |
+-----------------+
| REPEATABLE-READ |
+-----------------+

mysql> start transcation;

mysql> select * from temp where id=0;
Empty set (0.03 sec)

mysql> insert temp (id,des) values(0,'0');
Query OK, 1 row affected (0.11 sec)

mysql> commit;
Query OK, 0 rows affected (0.02 sec)
好像很好。

但是,对于我的情况,有可能同时进行多次NULL检查事务。

Trans 1:                                             Trans 2:

mysql> start transaction;                            mysql> start transaction;         

mysql> select * from temp where id=0;
Empty set (0.03 sec)

                                                    mysql> select * from temp where id=0;
                                                    Empty set (0.03 sec)

mysql> insert temp (id,des) values(0,'0');
Query OK, 1 row affected (0.11 sec)

                                                    mysql> insert temp (id,des) values(0,'0');


mysql> commit;
Query OK, 0 rows affected (0.02 sec)

                                                    --block and waiting for the Trans 1 commit;
                                                    ERROR 1062 (23000): Duplicate entry '0' for key 'PRIMARY'
当Trans 1提交时,Trans 2将报告ERROR 1062。我想避免错误,我认为它是应用程序中的NULL检查的普遍现象。

如何以正确的方式在mysql中实现多个NULL检查事务?使用"选择"有没有办法阻止对方sql在多个transcation?

谢谢。

更新2016.07.12

我只是简化了上面遇到的情况。事实上,我所拥有的表格类似于

mysql> create table temp
(
id int NOT NULL AUTO_INCREMENT,
des varchar(100),
unique_id int,
primary key (id),
UNIQUE (unique_id)
);

我的交易是

Trans 1:                                            Trans 2:

mysql> start transaction;                           mysql> start transaction;         

mysql> select * from temp where unique_id=0;
Empty set (0.06 sec)

                                                    mysql> select * from temp where unique_id=0;
                                                    Empty set (0.02 sec)

mysql> insert temp(des,unique_id) values('0',0);
Query OK, 1 row affected (0.20 sec)

                                                    mysql> insert temp(des,unique_id) values('0',0);


mysql> commit;
Query OK, 0 rows affected (0.02 sec)

                                                    --block and waiting for the Trans 1 commit;
                                                    ERROR 1062 (23000): Duplicate entry '0' for key 'unique_id'

因此PRIMARY KEY在我的实际案例中是AUTO_INCREMENT。

1 个答案:

答案 0 :(得分:0)

如果您坚持自己插入主键,而不是自动增加主键,那么这正是事务旨在创建的预期和期望的行为。

如果您希望提交Trans 2,则需要指定主键,或处理应用程序中的主键分配

相关问题