I want to implement the NULL check logic in the MYSQL. Here is the code:
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)
It seems well.
However, there is the possibility of multiple NULL check transaction at the same time for my situation.
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 2 will report the ERROR 1062 when Trans 1 commit. I want to avoid the Error and I think it is a universal phenomenon of NULL check in the application.
How to implement the multiple NULL check transaction in mysql in the correct way? Are there any ways to block each other when using the "select" sql in the multiple transcation?
Thank you.
update 2016.07.12
I just simplify the situation I meet with above. In fact, the table I have is similar to
mysql> create table temp
(
id int NOT NULL AUTO_INCREMENT,
des varchar(100),
unique_id int,
primary key (id),
UNIQUE (unique_id)
);
And my transactions are
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'
So the PRIMARY KEY is AUTO_INCREMENT in my real case.