MySQL(四)数据表操作

1 查看数据表
查看当前数据库中所有表
show tables;
查看表结构
desc 表名;
2 创建数据表

CREATE TABLE table_name(
       column1 type [约束 comment 注释],
       column2 type, column3 type, 
            ..... 
      columnN type, 
      PRIMARY KEY(one or more columns) ); 

注意:最后一个字段后不能添加逗号
例:创建职员表
comment 为字段的注释,可选

CREATE TABLE employee( 
      id INT PRIMARY KEY AUTO_INCREMENT COMMENT '职员编号', 
      emp_name VARCHAR(50) COMMENT '职员姓名', 
      emp_date DATETIME COMMENT '入职时间' 
      )DEFAULT CHARACTER SET 'UTF8MB4';

3 修改表结构
数据表创建完成后,在需求变动时可能需要对数据表中的字段进行修改、增加、删除等各种维护操作

  • 增加字段
alter table 表名 add 字段名 类型 [first/after 列名]; 
例:
-- 末尾添加一列:地址 
alter table employee add address varchar(200); 
-- 指定位置添加一列:生日 
alter table employee add birthday datetime after emp_name; 
-- 开头位置 
alter table employee add empid int first;

查看表结构 desc employee;

  • 删除字段
alter table 表名 drop 字段名; 
例:
alter table employee drop empid;
  • 修改字段
  1. 修改字段:修改名字和类型约束
alter table 表名 change 原名 新名 类型及约束; 
例:
-- 修改字段名 
alter table employee change emp_name empname varchar(100);
  1. 修改字段:修改类型约束
alter table 表名 modify 字段名 类型及约束;
 -- 修改是否为空 
alter table employee modify empname varchar(100) not null;
  1. 修改默认值
alter table 表名 alter 字段名 set default "默认值"; 
-- 修改地址默认值 
alter table employee alter address set default "空";

4 删除表

drop table 表名; 
例:
drop table class;

5 重命名表

RENAME TABLE 原名 TO 新名;
 --修改表名 
rename table employee to emp;

6 查看表的创建语句

show create table 表名; 
例:
show create table emp;
原文地址:https://www.cnblogs.com/duxiangjie/p/14205180.html