MySQL关于check约束无效的解决办法

首先看下面这段MySQL的操作,我新建了一个含有a和b的表,其中a用check约束必须大于0,然而我插入了一条(-2,1,1)的数据,其中a=-2,也是成功插入的。

所以MySQL只是check,但是不强制check。

复制代码
 1 mysql> create table checkDemoTable(a int,b int,id int,primary key(id));
 2 Query OK, 0 rows affected
 3 
 4 mysql> alter table checkDemoTable add constraint checkDemoConstraint check(a>0);
 5 Query OK, 0 rows affected
 6 Records: 0  Duplicates: 0  Warnings: 0
 7 
 8 mysql> insert into checkDemoTable values(-2,1,1);
 9 Query OK, 1 row affected
10 
11 mysql> select * from checkDemoTable;
12 +----+---+----+
13 | a  | b | id |
14 +----+---+----+
15 | -2 | 1 |  1 |
16 +----+---+----+
17 1 row in set
复制代码

 

解决这个问题有两种办法:

1. 如果需要设置CHECK约束的字段范围小,并且比较容易列举全部的值,就可以考虑将该字段的类型设置为枚举类型 enum()或集合类型set()。比如性别字段可以这样设置,插入枚举值以外值的操作将不被允许。

复制代码
 1 mysql> create table checkDemoTable(a enum('',''),b int,id int,primary key(id));
 2 Query OK, 0 rows affected
 3 
 4 mysql> insert into checkDemoTable values('',1,1);
 5 Query OK, 1 row affected
 6 
 7 mysql> select * from checkDemoTable;
 8 +----+---+----+
 9 | a  | b | id |
10 +----+---+----+
11 || 1 |  1 |
12 +----+---+----+
13 1 row in set
复制代码

2. 如果需要设置CHECK约束的字段范围大,且列举全部值比较困难,比如:>0的值,那就只能使用触发器来代替约束实现数据的有效性了。如下代码,可以保证a>0。

复制代码
 1 mysql> create table checkDemoTable(a int,b int,id int,primary key(id));
 2 Query OK, 0 rows affected
 3 
 4 mysql> delimiter ||  
 5 drop trigger if exists checkTrigger||  
 6 create trigger checkTrigger before insert on checkDemoTable for each row 
 7 begin  
 8 if new.a<=0 then set new.a=1; end if;
 9 end||  
10 delimiter;
11   
12 Query OK, 0 rows affected
13 Query OK, 0 rows affected
14 
15 mysql> insert into checkDemoTable values(-1,1,1);
16 Query OK, 1 row affected
17 
18 mysql> select * from checkDemoTable;
19 +---+---+----+
20 | a | b | id |
21 +---+---+----+
22 | 1 | 1 |  1 |
23 +---+---+----+
24 1 row in set
复制代码

 

posted on   wangtianze  阅读(16665)  评论(2编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示