~ DDL 操作表

创建一张数据表

创建数据表,需要以下信息:

  • 必选 _ 数据表名
  • 必选 _ 字段名称  数据类型(长度)  &  可选 _ 字段约束、索引、注释

# 基本语法
create table [if not exists] 表名(
 字段1 数据类型(长度) [字段约束] [索引] [注释],
 字段2 数据类型(长度) [字段约束] [索引] [注释],
 ...
 字段n 数据类型(长度) [字段约束] [索引] [注释]
)[表类型][表字符集][注释];

# 代码示例

CREATE TABLE student(
	studentNo INT(4) NOT NULL PRIMARY KEY COMMENT '学号',
	studentName VARCHAR(50) NOT NULL COMMENT '学生名称'
)COMMENT="学生表";

删除一张数据表

# 基本语法
drop table [if exists] 表名;

# 代码示例

drop table student;

修改表名

# 基本语法
rename table 表名 to 新表名;

# 代码示例

rename table student to hello;

修改表结构

  • 添加字段
# 基本语法
alter table 表名 add 字段名 数据类型(长度) [字段约束];

# 代码示例

alter table hello adds studphone varchar(20) not null;  // 在表的最后位置添加字段
  • 删除字段
# 基本语法
alter table 表名 drop 字段名;

# 代码示例

alter table hello drop stuphone;
  • 修改字段
# 修改列名:alter table 表名 change 旧列名 新列名 数据类型(长度) [字段约束];

# 代码示例

alter table hello change studentname stuname varchar(40) not null;
# 修改字段的数据类型和字段约束:alter table 表名 modify 列名 数据类型 [字段约束];

# 代码示例

alter table hello modify stuname varchar(20) not null;
  • 添加主键约束
# 基本语法
alter table 表名 add constraint 主键名 primary key 表名(主键字段);

# 代码示例

# 创建人员表
create table person(
   person_id int not null,
     # person_id int not null primary key,   也可以直接添加主键
   person_name varchar(40) not null,
   person_sex varchar(20) not null
)comment='人员';

# 添加主键
alter table person add constraint person_pk primary key person (person_id);

查看表结构

# 查看一个数据库中的所有表

show tables;

# 查看表结构

describe 表名;