Mysql添加约束:强制字段获取特定值

时间:2011-03-01 15:07:39

标签: mysql sql constraints

我有一个简单的mysql表,其中包含以下属性:Name, Surname, Role

我希望“角色”字段仅获取2个可能的值:SupervisorOperator,并在查询尝试插入与该2个值不同的内容时导致错误。

例如,我希望以下查询返回错误:

INSERT INTO tablename (name,surname,role) VALUES ('max','power','footballplayer');

我尝试将字段Role设置为ENUMSET类型,但它会将字段留空而不是触发和错误:(

3 个答案:

答案 0 :(得分:2)

您需要更改sql_mode以避免插入。

mysql> create table check_values (
    -> id int not null auto_increment primary key,
    -> name varchar(50),
    -> role enum ('max','power','fp')
    -> )engine = myisam;
Query OK, 0 rows affected (0.01 sec)

mysql> set sql_mode = '';
Query OK, 0 rows affected (0.00 sec)

mysql> insert into check_values (name,role) values ('nick','max');
Query OK, 1 row affected (0.00 sec)

mysql> insert into check_values (name,role) values ('john','other');
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> show warnings;
+---------+------+-------------------------------------------+
| Level   | Code | Message                                   |
+---------+------+-------------------------------------------+
| Warning | 1265 | Data truncated for column 'role' at row 1 |
+---------+------+-------------------------------------------+
1 row in set (0.00 sec)

mysql> select * from check_values;
+----+------+------+
| id | name | role |
+----+------+------+
|  1 | nick | max  |
|  2 | john |      |
+----+------+------+
2 rows in set (0.00 sec)

mysql> set sql_mode = 'traditional';
Query OK, 0 rows affected (0.00 sec)

mysql> insert into check_values (name,role) values ('frank','other');
ERROR 1265 (01000): Data truncated for column 'role' at row 1
mysql> select * from check_values;
+----+------+------+
| id | name | role |
+----+------+------+
|  1 | nick | max  |
|  2 | john |      |
+----+------+------+
2 rows in set (0.00 sec)

答案 1 :(得分:0)

当您使用枚举时,您是否看到任何错误? http://dev.mysql.com/doc/refman/5.0/en/enum.html

另一种方法是创建具有允许角色的查找类型的表,并从该表创建外键约束到角色表。如果你在多个地方使用检查约束,或者你有一个更大的值列表要检查,那将更合适。

我相信,MYSQL不直接支持检查约束,如果这就是你要找的东西。检查这些链接。

CHECK constraint in MySQL is not working

MySQL and Check Constraints

Using Foreign Keys to replace check constraint

答案 2 :(得分:0)