数据库操作之数据约束

时间:2019-05-12 16:24:52   收藏:0   阅读:154

1、创建表时数据默认值的设置:(默认值可以为NULL)

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

2、数据的非空限制:

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

3、数据的唯一性的设置:(可以插入多个NULL,不是重复,是都没有值)

create table 表名(
        字段名 字段类型 unique,
        字段名 字段类型
)

4、主键:(非空+唯一)

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

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

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

6、外键约束(减少冗余):(正常字段1与字段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)                      
)      

注:

添加数据时先添加主表;删除及修改数据时先删除、修改副表。

 

原文:https://www.cnblogs.com/21-forever/p/10852625.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!