注意:这里的表操作所有的前提都是要进入到数据库中使用(use 数据库名)
一.查询
① 查询当前数据库所有表: show tables;
② 查询表结构: desc 表名;
③ 查询指定表的建表结构: show create table 表名;
二.创建
① 创建表
create table 表名(
字段1 字段1类型【comment 字段1注释】,
字段2 字段2类型 【comment 字段2注释】,
字段3 字段3类型 【comment 字段3 注释】,
.........
字段n 字段n类型 【comment 字段n注释】(最后的字段后面不用加逗号)
)【comment 表注释】;
列题:创建下面的表,表名是text
id | name | age | gender |
create table text (
id int comment '编号' ,
name varchar(50) comment '姓名',
age int comment '年龄',
gender varchar(1) comment '性别' (字符串类型,是因为性别要么是男要么是 女,所以只要一个长度就可以了)
);
三.修改
①添加字段:alter table 表名 add 字段名 类型(长度)【comment 注释】【约束】;
列题:为emp表添加一个新字段“昵称”为nice类型为varchar(20)
alter table emp add nice varchar(20);
②修改数据类型:alter table 表名 modify 字段名 新数据类型(长度);
③修改字段名和字段类型:alter table 表名 change 旧字段名 新字段名 类型(长度) 【comment 注释】;
列题:将emp表的nice字段名修改为username 类型修改为varchar(30);
alter table emp change nice username varchar(30);
④ 删除字段: alter table 表名 drop 字段名;
列题:将emp表的username字段删除
alter table emp drop username ;
⑤ 修改表名:alter table 表名 rename to 新表名;
列题:将emp表名修改为wangchu
alter table emp rename to wangchu;
四.删除
①删除表:drop table 【if exists】表名;
②删除指定表并重新创建该表:truncate table 表名;
注意:删除表时表中的数据也会被一并删除,再次重新创建后表中的数据都没了