表操作
2.查看表结构
show create table table_name; -- 终端中以表格的方式组织数据
show create table table_name\G -- 表示一行行显示信息
desc t1: -- 以清晰明了的方式显示,完整写法为 describe t1;
3.修改表结构
语法
1. 修改表名
ALTER TABLE 表名
RENAME 新表名;
2. 增加字段
ALTER TABLE 表名
ADD 字段名 数据类型 [完整性约束条件…],
ADD 字段名 数据类型 [完整性约束条件…];
ALTER TABLE 表名
ADD 字段名 数据类型 [完整性约束条件…] FIRST; -- FIRST表示添加的位置为第一个
ALTER TABLE 表名
ADD 字段名 数据类型 [完整性约束条件…] AFTER 字段名; -- AFTER表示将新添加的放在哪个字段之后
3. 删除字段
ALTER TABLE 表名
DROP 字段名;
4. 修改字段
ALTER TABLE 表名
MODIFY 字段名 数据类型 [完整性约束条件…];
ALTER TABLE 表名
CHANGE 旧字段名 新字段名 旧数据类型 [完整性约束条件…];
ALTER TABLE 表名
CHANGE 旧字段名 新字段名 新数据类型 [完整性约束条件…];
示例
1.修改储存引擎,表名
> alter table t1 engine=innodb;
> alter table t1 rename t2;
2.添加字段
> alter table student
> add name varchar(20) not null, -- varchar是可变长字符类型,
> add age int(3) not null default 22, -- int 数据类型指定的宽度表示显示的宽度,与储存毫无关系
> add gender enum("male","female") default "male"
> ;
> alter table student
> add stu_num char(10) not null after name, -- 将字段加在name字段前面
> add id int auto_increment first; -- 将字段id 添加到最前面
3.删除字段
> alter table student
> drop stu_num;
> alter table student
> drop id;
4.修改字段类型
> alter table student modify
> id int(11) not null primary key auto_increment;
-- 将该字段修改为主键,增加约束不为空,自动增长(默认从1开始,步长为1)
> alter table student change
> sname name char(10) not null; -- 修改字段的名称
5.对以存在的表增加复合主键
> alter table student
> add primary key(id,name);
6.删除主键
-- 删除自增约束
> alter table student modify
> sid int(11) not null;
-- 删除主键
> alter table student
> drop primary key;
4.复制表
复制表结构+记录(主键,外键和索引不会被复制)
> create table new_one select * from studnet;
只复制表结构(主键,外键和索引不会被复制)
> create table new_two select * from student where 1=2; -- 故意将条件设置为假!
拷贝表结构(只有结构,包含主键、约束、索引,没有数据!)
> create table new_three like student;
5.删除表
> drop table table_name;