gpt4 book ai didi

mysql - mysql中如何实现多次NULL检查事务

转载 作者:行者123 更新时间:2023-11-29 20:47:57 24 4
gpt4 key购买 nike

我想在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。我想避免这个错误,我认为这是应用程序中空检查的普遍现象。

如何正确实现mysql中的多次NULL检查事务?在多笔交易中使用“select”sql时有什么办法可以互相阻塞吗?

谢谢。

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'

因此,在我的实际情况中,主键是 AUTO_INCRMENT。

最佳答案

如果您坚持自己插入主键,而不是让它自动增量,那么这正是事务设计要创建的预期和期望行为。

如果您希望Trans 2提交,那么您需要不指定主键,或者在您的应用程序中处理主键分配.

关于mysql - mysql中如何实现多次NULL检查事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38299751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com