数据库
六、表的操作
表是建⽴在数据库中的数据结构,是⼀类数据的存储 集。
表的创建
create table [if not exists] `表的名字`(
id int not null auto_increment primary key comment '主 键',
account char(255) comment '⽤⼾名' default 'admin',
pwd varchar(65535) comment '密码' not null
) engine=myisam charset=utf8mb4;
备注:
- 字符集如果不指定, 默认继承库的字符集。
- engine 默认innodb。
查看所有的表
选择数据库后,才能查看表
show tables;
删除表
drop table [if exists] `表名`;
显⽰建表结构
desc `表名`;
describe `表名`;
修改表
-- 修改表的名称
alter table `old_name` rename `new_name`;
-- 修改表的引擎
alter table `表名` engine = innodb|myisam;
-- 移动表到指定的数据库
alter table `表名` rename to 数据库名.表名;
修改字段
-- 增加⼀个新的字段
alter table `表名` add `字段名` 数据类型 属性;
-- 增加⼀个新的字段, 并放在⾸位
alter table `表名` add `字段名` 数据类型 属性 first;
-- 增加⼀个新的字段, 并放在某⼀个字段之后
alter table `表名` add `字段名` 数据类型 属性 after 指定 字段;
-- 修改字段的属性
alter table `表名` modify `字段名` 数据类型 属性;
-- 修改字段的名称
alter table `表名` change `原字段名` `新的字段名` 数据 类型 属性;
-- 修改字段的位置
alter table `表名` change `原字段名` `新的字段名` 数据 类型 after `指定字段`;
-- 删除字段
alter table `表名` drop `字段名`;
复制表
- ⾸先在创建⼀个表,并在表中插⼊⼀些数据
/* 创建 abc 表*/
create table abc(
id int primary key auto_increment comment '主键',
username char(32) not null comment '账⼾',
password char(32) not null comment '密码'
) engine=myisam;
/* 插⼊两条数据 */
insert into abc values(null, 'tom', md(123456)), (null, 'bob', md(123456));
- 复制表,并且复制数据
- 执⾏下列语句
- create table `复制表的名称` select * from `原表名`;
- #特点: 完整的复制⼀个表,既有原表的结构,⼜有原表的数 据,不能复制主键
- 仅复制表结构, 不复制数据
create table `复制表的名称` like `原表名`;
#特点: 复制后的表结构与原表相同,但是⾥⾯没有数据,是 ⼀张空表,可以复制主键
-- 复制数据
insert into `复制表的名称` select * from `原表名`;