DDL语句
1、创建库
- create database test default character set utf8;
- drop database test;
2、创建表
(创建表的列,列名和类型)
- create table employees(employee_id int,employee_name varchar(30),salary float(8,2));
- drop table employees;
3、修改表
- alter table employees(表的名字) rename emp(表的名字) ; 修改表名字
- alter table emp(表的名字) change column employee_name(列的名字) emp_name varchar(30); 修改列的名字
- alter table emp(表的名字) modify emp_name(列的名字) varchar(40); 修改列的长度
- alter table emp add column commission_pct float(4,2); 增加新列
- alter table emp drop column commission_pct; 删除列
- show databases;
- show tables;
- desc 表的名字; 查看表结构
4、创建表时指定约束
- 非空约束(not null)
- 唯一性约束(unique)
- 主键约束(primary key)PK
- 外键约束(foreign key)FK
示例1: department_id主键约束并且自动增长;department_name 不允许重复不允许有空值;location_id 不允许为空:
- create table departments(department_id int primary key auto_increment,department_name varchar(30) no null unique,location_id int not null);
- show keys from departments; 查询
示例2:创建employees表,包含employee_id,设该列为主键并且自动增长;last_name列不允许含有空值;dept_id为外键参照departments表的主键:
- create table employees(employee_id int primary key auto_increment,last_name varchar(30)not null,dept_id int,constraint emp_fk foreign key(dept_id) references departments(department_id));
外键部分语句:constraint ...
5、采用修改表的方式完成约束的添加与删除
5.1、对指定列增加主键约束:
- alter table emp add primary key(employee_id);
- alter table emp modify employee_id int auto_increment; 添加自增长
5.2、删除主键约束:
- ps:若主键有自增长,需要先删除自增长,再删除主键。
- alter table emp modify employee_id int; 去除自动增长
- alter table emp drop primary key; 删除主键
5.3、非空约束:
- 添加非空约束:alter table 表名 modify 列名 类型 not null;
- 删除非空约束:alter table 表名 modify 列名 类型 null;
5.4、唯一性约束:
- 添加: alter table 表名 add constraint 约束名 unique(列名);
- 删除: alter table 表名 drop key 约束名;
5.5、外键约束:
- 添加: alter table 表名 add constraint 约束名 foreign key(列名) references 参照的表明(参照的列名);
- alter table 表名 drop foreign key 约束名; 删除外键约束
- alter table 表名 drop index 约束名; 删除外键约束时必须删除索引名(创建外键时会把外键放到索引中)