温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

mysql表级别约束讲解

发布时间:2020-04-24 15:35:34 来源:亿速云 阅读:216 作者:三月 栏目:MySQL数据库

本文主要给大家介绍mysql表级别约束讲解,其所涉及的东西,从理论知识来获悉,有很多书籍、文献可供大家参考,从现实意义角度出发,亿速云累计多年的实践经验可分享给大家。

表级别的约束

1. 主键约束----primary key

主键:表中一个列或者多个列的组合,要求该列的数据唯一

单字段主键:字段名 数据类型 属性 primary key

多字段主键:primary key (字段1,字段2

主键列的值不能为空!!!

 mysql表级别约束讲解

例子:创建一张员工表tb_emp1,以id为主键

    create table tb_emp1(id int primary key,name varchar(25),deptid int,salary float);             创建一张员工表tb_emp1,以idname为组合主键

    create table tb_emp3(id int,name varchar(25),deptid int,salary float,primary key(id,name));


2. 自动增长----auto_incerment

只作用于主键,是数值型的自动增长

 例子:

    create table tb_emp4(id int primary key auto_increment,name varchar(25),deptid int,

salary float);


3. 非空约束----not null

Create 表名(列名 类型 not null

 

4. 默认值约束----default

Create 表名(列名 类型 not null default 数值)

 

    create table tb_emp6(id int primary key auto_increment,name varchar(25) not null,

deptid int not null default 1,salary float not null default 5000);


5. 外键----foreign key

外键主要用来将两个表的数据进行连接

create 表名(列名 类型 属性,constraint 外键名称 foreign key(列名)

references 另一个表名(列名));

注意:建立外键连接的两个字段的类型、属性要一致!!!

 

    例子:建立部门表 tb_dept7、员工表tb_emp7,将两张表的deptid建立外键约束

    create table tb_dept7(id int primary key,name varchar(20));

注:部门表要先插入数据才能建立员工表

    create table tb_emp7(id int primary key auto_increment,name varchar(25) not null,

deptid int not null default 1,salary float not null default 5000,constraint fk_emp7_dept7 foreign key(deptid) references tb_dept7(id));

  

    删除外键:因为可以有多个外键,所以要有名称

    要删除建立外键连接的表数据时,要先解除外键连接

    alter table 表名drop foreign key 外键名称;

            

         删除主键:alter table 表名 drop primary key;

        如果主键字段是自增时,不能直接删除,要先改定义把自增删除!

看了以上介绍mysql表级别约束讲解,希望能给大家在实际运用中带来一定的帮助。本文由于篇幅有限,难免会有不足和需要补充的地方,大家可以继续关注亿速云行业资讯板块,会定期给大家更新行业新闻和知识,如有需要更加专业的解答,可在官网联系我们的24小时售前售后,随时帮您解答问题的。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI