数据库的数据约束

什么数据约束:

        对用户操作表的数据进行约束。

1.默认值(缺省约束)

作用: 当用户对使用默认值的字段不插入值的时候,就使用默认值。

create table 表名(
        字段名 字段类型 default 默认值 ,
        字段名 字段类型
)

2.非空    

作用: 限制字段必须赋值

create table 表名(
        字段名 字段类型 not null,
        字段名 字段类型
)
  

3.唯一(非空+唯一)

create table 表名(
        字段名 字段类型 primary key ,
        字段名 字段类型,
        字段名 字段类型       
)   

4、自增长(必须是int类型,而且是主键)

create table 表名(
        字段名 字段类型 primary key auto_increment,
        字段名 字段类型,
        字段名 字段类型       
)   

5、 外键

作用:约束两种表的数据

create table 表名1(
        字段名1 字段类型1 primary key ,
        字段名2 字段类型2
)   


create table 表名2(
        字段名3 字段类型3 primary key ,
        字段名4 字段类型4,
        字段名5 字段类型5
       constraint 外键名字(如 fk_表1_表2)foreign key (字段名5) references 表1(字段1)                     
)

猜你喜欢

转载自www.cnblogs.com/heitaitou/p/12746403.html