I am new to MySql, I am trying to create a table which will store scores ranging from 0 to 5. I keep reading about the constraint CHECK but it fails, it allows me to input numbers greater than 5.
Here is a sample of my script
create table part2(
P2_Q1 int(1)
check (P2_Q1 >= 0 and P2_Q1 < 6), //this is one way I've read
P2_Q2 int(1)
check (P2_Q2 >= 0 and P2_Q2 < 6),
P2_Q3 int(1)
check (P2_Q3 between 0 and 5), //and this is the other way
P2_Q4 int(1)
check (P2_Q4 between 0 and 5)
);
Thanks ahead of time for any help I can get!
You can define check constraints in MySQL but it has no effect. The engine just ignores whatever you define. It may be supported in a future version of MySQL.
But instead you can define 2 triggers that will be called on every update and insert. Insert trigger:
delimiter |
CREATE TRIGGER `ins_p2` BEFORE INSERT ON `part2`
FOR EACH ROW BEGIN
IF NEW.P2_Q1 not between 0 and 5
and NEW.P2_Q2 not between 0 and 5
and NEW.P2_Q3 not between 0 and 5
and NEW.P2_Q4 not between 0 and 5
THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'out of range error';
END IF;
END
|
delimiter ;
And you can do the same for updates.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.