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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM