Mysql数据库_DDL.sql

来源:互联网 发布:剑三破军道姑捏脸数据 编辑:程序博客网 时间:2024/06/08 06:00
/*
//建表
//
*/
create table tb_emp( --创建
id int primary key auto_increment, --主键,自增长
name varchar(18),
sex varchar(2),
age int,
address varchar(200),
email varchar(100)
);
 create table tb_dept(
 id int primary key auto_increment,
 name varchar(18) unique, --
 );


drop table tb_emp; --删除


alter table tb_emp modify age(varchar); --更改列的类型
alter table tb_emp add phone varchar(18); --增加列
alter table tb_emp drop phone; --删除列
alter table tb_emp change name my_emp varchar(18); --列改名
alter table tb_emp rename 新表名; --更改表名
rename table tb_emp to 新表名; --更改表名


/*
//auto_increment mysql特有
//约束是在表上强制执行的数据校验规则
//约束主要用于保证数据库的完整性
//当表中数据有相互依赖性时,可以保护相关的数据不被删除
//大部分数据库支持下面五类完整性约束
//not null 非空
//unique key 唯一键
//primary key 主键
//foreign key 外键
//check 检查
//在建表的同时创建
*/
/*1.
//主键从功能上看相当于非空且唯一
//一个表中只允许一个主键
//主键字段可以是单子段或者多字段的组合,联合主键
//当监理主键约束时,mysql为主键创建对应的索引
//主键约束总为primary
*/
create table tb_emp( --创建
id int primary key auto_increment, --主键,自增长
name varchar(18) not null, --非空约束
sex varchar(2),
age int check (age >18 and age <60), --检查约束(在mysql中不起作用)
address varchar(200)
/*外键约束
//#外键参照的只能是主表tb_dept主键或者唯一键
//#tb_emp里面的detp_id引用自tb_dept表,如果部门没有id为3的部门,这个字段的值不能为3
//#当tb_emp表里面有dept_id为3的数据,就不能删除tb_dept表里面id为3的记录,因为有关联引用
*/
dept_id int references tb_dept(id),
);


/*
//插入数据测试
*/
 insert into tb_emp(name,sex,age,address,email,dept_id)
 values('luo','男',23,'zg','tom@163.com',1);
 
 
 /*
 //2.在建表后创建约束
 */
 create table tb_emp( --创建
id int ,
name varchar(18) not null,
sex varchar(2) check(sex='男' or sex='女'),
age int,
address varchar(200),
email varchar(100) unique,
dept_id int
);
alter tabel tb_emp
add primary key (id);--外部添加主键
alter table tb_emp
add column id int auto_increment; --自动增长
alter table tb_emp
add unique (email); --外部天健唯一键
alter table tb_emp
#constraint foreign key 外键名(外键) references 主表(字段);--外部添加外键
add constraint foreign key tb_emp_fk(dept_id) references tb_dept(id);
alter table tb_emp
add constraint check (age > 18 and age < 60); --外部添加检查约束
 /*
 //3.在建表末尾创建约束
 */
  create table tb_emp( --创建
id int ,
name varchar(18) not null,
sex varchar(2) default '男' check(sex='男' or sex='女'),
age int,
address varchar(200),
email varchar(100) unique,
dept_id int
alter table tb_emp
#constraint foreign key 外键名(外键) references 主表(字段);
add constraint foreign key tb_emp_fk(dept_id) references tb_dept(id);
);
 
 
 
 /*
 //删除约束
 */
 #1.修改非空约束
 alter table tb_emp modify name varchar(18);
 #2.删除唯一约束
 alter table tb_emp  drop index email;
 #3.删除主键约束 注意自动增长问题
 alter table tb_emp modify id key;
 alter table tb_emp drop primary key;
 #4.删除外建约束
 alter table tb_emp drop foreign key tb_emp_fk(这个名字不确定看系统给出的);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0 0
原创粉丝点击