DDL
数据定义语言,用于操作数据库对象的结构
- 数据库的创建和销毁
# 创建数据库
create database [if not exists] bd1906;
#销毁数据库
drop database [if exists] bd1906;
- 表的创建,修改和销毁
1. 创建表
create table student(
sid int,
sname varchar(20),
age int,
gender varchar(10)
);
# 查看表的状态
desc student;
2. 修改结构(添加字段,销毁字段,修改字段(字段名称,类型,长度,位置,约束等))
alter table tname add/drop/change/modify colname coltype... first|after
* 添加字段
追加字段
alter table student add email varchar(20);
添加到首列
alter table student add phone char(11) first;
指定位置:
alter table student add card char(18) after sid;
* 销毁字段
alter table student drop card;
* 修改字段
alter table student modify colname 类型 约束...
alter table student change 旧字段名称 新字段名称 类型 约束...
# 修改字段名称
alter table student change email semail varchar(20);
# 修改字段的类型和长度
alter table student modify sname varchar(50);
# 修改位置
alter table student modify semail varchar(20) after sname;
3.销毁表
drop table student;
4.修改表的名称
rename table student to stu;
5.清空表(只清空数据,不改变结构)
truncate table stu;
delete,truncate和drop的区别?
drop销毁表结构;
truncate不改变结构,只清空数据和重置。
- 数据类型(仅限mysql)
数值类型:
整数:
int / bigint
浮点数:
float(10,2): 长度是10,小数点后的位数是2
double(16,4): 长度为16,小数点后的位数是4
decimal(m,n): 金额等数据时必须使用decimal
字符串类型:必须指明长度
char(n): 固定长度
varchar(n): 可变长度
日期类型:
date: 日期
time: 时间
datetime: 日期和时间
timestamp: 时间戳
其他类型:
text: 文本类型
blob: 二进制数据类型
enum() / set() / json()
数据完整性
数据的准确性和可靠性
实体完整性
实体指的就是记录,就是保证记录是准确的,不重复的
- 主键约束: 唯一而且不能为空(primary key)
# 场景1: 创建表的同时添加约束
create table student(
sid int primary key,
sname varchar(20)
);
create table student(
sid int,
sname varchar(20),
primary key(sid)
);
# 场景2: 表已经存在(主键字段绝对不能存在重复的数据)
alter table stu add constraint PK_ID primary key (sid);
# 注意:
1.每张表必须有主键,但是有且只能有一个,允许有联合主键
2.主键字段一般数据类型和长度尽可能小
3.主键字段不要使用业务字段
- 唯一约束: 字段的值必须唯一
create table student(
card char(18) unique
)
alter table stu add constraint UQ_CARD unique (card);
- 主键自增:
auto_increment: 默认从1开始每次增加1
域完整性
域:字段
类型约束
- not null:非空约束
- default: 默认值
引用完整性
其中一张表的字段取值需要依赖于另一张表
外键约束
alter table emp add constraint FK_DEPTNO foreign key(deptno) references dept(deptno);