55

解读MySQL的数据库约束

 6 years ago
source link: https://www.linuxprobe.com/mysql-restrict.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

数据库约束:约束是在表上强制执行的数据校验规则,主要用于保证数据库里数据的完整性。除此之外,当表中的数据存在相互依赖性时,可以保证相关的数据不被删除。

1.NOT NULL: 非空约束,指定某列不能为空,只能作为列级约束使用,只能使用列级约束语法定义。

SQL中的null值,null不区分大小写,具有如下特征:所有数据类型的值都可以是null,包括int、float、boolean等。空字符串不等于null,0也不等于null。建表时为指定列设置非空约束,只需在列定义后增加not null即可,例如:

create table t_test
(
    id int not null,
    name varchar(255) default 'xyz' not null,
    gender varchar(2) null
);

使用alter table修改表时增加或删除非空约束,例如:

#增加非空约束
alter table t_test modify gender varchar(2) not null;
#取消非空约束
alter table t_test modify gender varchar(2) null;
#取消非空约束,并指定默认值
alter table t_test modify name varchar(255) default 'abc' null;
2.UNIQUE: 唯一约束,指定某列或者几列组合不能重复。

虽然唯一约束的列不可以出现重复值,但可以出现多个null值,因为在数据库中null不等于null。同一个表内可创建多个唯一约束,唯一约束也可有多列组合而成。 当为某列创建唯一约束时,MySQL会为该列创建唯一索引, 如果不给唯一约束起名,该唯一约束默认与列名相同。唯一约束可以使用列级语法建立,也可以使用表级语法建立。 如果是为多列建立组合约束,或者需要为约束指定约束名,则只能使用表级语法。

使用列级语法建立唯一约束,只需要在列定义后增加unique关键字即可:

#创建表时建立唯一约束,使用列级语法建立
create table unique_test
(
    #建立非空约束,意味着id不能为null
    id int not null,
    #建立唯一约束,意味着多行数据的该列值不能相等
    name varchar(255) unique
);

表级语法创建唯一约束的格式:[constraint 约束名] unique (列名[,列名,...]),上面的表级约束语法格式既可以放在create table语句中与列定义并列,也可以放在alter table语句中使用add关键字添加:

#创建表时,使用表级语法创建唯一约束
create table uniques_test2
(
    #为id建立非空约束,意味着id不能为null
    id int not null,
    name varchar(255),
    pass varchar(255),
    #使用表级语法为name建立唯一约束
    unique (name),
    #使用表级语法为pass建立唯一约束,并指定约束名为test2_uk
    constraint test2_uk unique (pass)
);

#创建表时,使用表级语法建立组合列的唯一约束
create table unique_test3
(
    id int not null,
    name varchar(255),
    pass varchar(255),
    #指定name和pass两列组合不能重复
    constraint test3_uk unique (name, pass)
);

#在修改表时,使用add关键字来增加唯一约束
alter table unique_test3 add unique (id, name);
#在修改表时,使用modify关键字,来为单列设置唯一约束
alter table unique_test3 modify name varchar(100) unique;

MySQL中删除唯一约束:

alter table tableName drop index 约束名;
    例句:
#删除unique_test3表中的test3_uk唯一约束
alter table unique_test3 drop index test3_uk;
3.PRIMARY KEY: 主键约束,指定该列的值可以唯一地标识该条记录。
4.FOREIGN KEY: 外键约束,指定该行记录从属于主表中的一条记录,主要用于保证参照完整性。
5.CHECK(MySQL不支持): 检查约束,指定一个布尔表达式,用于指定对应列的值必须满足该表达式。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK