直接将约束定义到在列的声明里
使用示例:
-- id、姓名、年龄、性别、身高、生日 create table if not exists t_person( p_id int primary key,-- 主键 p_name varchar(50) unique not null,-- 唯一+非空 age tinyint unsigned not null,-- 非空 无符号数 0-255 sex enum('男','女','奥特曼') default '奥特曼',-- 默认 height decimal(4,1), -- 总共有4位,小数点占1位:000.0 birthday datetime )
3.2、表级约束
将约束单独定义在所有列的下方,not null和default没有表级约束
语法:[constraint 自定义约束名] 约束类型(字段名)
使用示例:
create table if not exists t_person( p_id int,-- 主键 p_name varchar(50) not null,-- 唯一+非空 age tinyint unsigned not null,-- 非空 无符号数 0-255 sex enum('男','女','奥特曼') default '奥特曼',-- 默认 height decimal(4,1), -- 总共有4位,小数点占1位:000.0 birthday datetime, -- 表级约束 primary key(p_id),-- 给p_id添加主键约束 constraint un_name unique(p_name)-- 给p_name添加唯一约束 )
3.3、外键约束
作用:用来表示两张表之间的联系,必须结合另一张表使用
特点:
- 连接的必须是另一张表的主键或者唯一列
- 外键列的值不可自定义,必须来自另一张表与之关联的列中已经存在的值
- 值可以为null,不唯一
- 必须用表级约束创建
语法:
foreign key(字段名) references 其他表名(其他表的连接字段名)
使用:
- 建表顺序:先建没有外键的表,再建有外键的表
- 删表顺序:先删有外键的,再删没外键的
- 外键列的数据类型必须与所连接的列一致
使用示例:
-- 班级表:id,班级名 create table t_class( c_id int PRIMARY KEY, c_name varchar(20) not null ) -- 学生表:id,姓名,所属班级id create table t_student( s_id int PRIMARY KEY, s_name varchar(20) not null, c_id int not null , -- 表级约束 FOREIGN KEY(c_id) REFERENCES t_class(c_id) )
4、表的销毁
语法:
drop table [if exists] 表名
注意事项:
在3.3外键约束具体使用中对于有外键的表,要先删除有外键的表,再删除没有外键的表
drop table t_student – 先删学生表
drop table t_class – 才能删班级表
到此这篇关于一文掌握MySQL表的创建和约束的文章就介绍到这了,更多相关MySQL表 创建 约束内容请搜索
更多相关Mysql内容来自木庄网络博客
标签:Mysql
相关阅读 >>
更多相关阅读请进入《mysql》频道 >>
数据库系统概念 第6版
本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。