MySQL学习笔记(六)

180 阅读3分钟

这是我参与11月更文挑战的第1天,活动详情查看:2021最后一次更文挑战

2、DDL语句

2.1 CREAT语句

  • 用于表的创建
2.1.1 表的创建
  • 格式:creat table 表名 (字段名 数据类型 , 字段名2 ,数据类型 , 字段名3 ,数据类型);

    • 建议以t_ 或者是 tbl_ 开始,可读性强
    • 字段名、表名:见名知意
    • 表名和字段名都属于标识符
    • 规范:所有的标识符都是小写,单词与单词之间通过下划线进行衔接
 【案例】:在test下创建一个学生表,其中性别的默认值设置为“男”
  create table t_student(
     no int ,
     name varchar(32),
     sex char(1) default 'm' ,
     age int(3),
     email varchar(255)
  );
  
  
 【案例】:创建一个用户表
 create table t_user(
     id int ,
     name varchar(32),
     birth date ,
     create_time  datetime 
 );
 ​
 ​
 // 快速创建表
 可以将一个查询结果制成一个新的表
 【案例】:将emp复制一份,成为新表,表名为emp2
 create table emp2 as select * from emp ;
2.1.2 mysql常见的数据类型
  • varchar(0~255):可变长度的字符串,根据实际长度动态分配空间
  • char(0~255):定长字符串,效率高,但是使用不当会造成空间浪费
  • int(0~11):整型
  • bigint:长整型
  • float:单精度浮点型
  • double:双精度浮点型
  • date:短日期类型 , 只包括年月日信息 默认格式:%Y-%m-%d
  • datetime:长日期类型,包括年月时时分秒日期 %Y-%m-%d %h:%i:%s
  • clob(>=255):字符大对象,最多存储4个G的字符串,比如简介、说明等
  • blob:二进制大对象,存储图片、声音、视频等流媒体数据 【插入数据时,用IO流】

2.2 DROP语句

  • 格式:

    • drop table t_student ; // 当表不存在时,会报错
    • drop table if exists t_student 更加健壮

2.3 TRUNCATE语句

  • 格式:truncate table 表名
  • 特点:物理删除 , 效率高 , 表会被一次截断 ; 不支持回滚
  // 快速删除表中的数据 ---- truncate语句
 【案例】:删除dept_bak表中的所有数据
  truncate table dept_bak ;
  
  当表非常大,上亿条记录时,可以选择使用此方法。

2.4 ALTER语句

  • 字段的增删改

    • 字段的增加

      • 格式:alter table 表名 add 新字段名 新字段数据类型 ;
    • 字段的删除

      • 格式:alter table 表名 drop 字段名 ;
    • 字段的修改

      • 对数据类型的修改

        • 格式:alter table 表名 modify 字段名 字段名新的数据类型 ;
      • 对数据名称的修改

        • 格式:alter table 表名 change 字段名 新字段名 新字段名的数据类型 ;
 // 对表的增加
 【案例】:向dept_bak中增加一个字段STURCT
 alter table dept_bak add STURCT varchar(40);
 ​
 // 对表的删除
 【案例】:删除字段名STRUCT
 alter table dept_bak drop STRUCT ;
 ​
 // 对表的修改
 【案例】:将STRUCT字段的数据类型修改为int型
 alter table dept_bak modify STRUCT int ;
 ​
 【案例】:将STRUCT字段的名称修改为S
 alter table dept_bak change STRUCT S char(2)  ;
  • 对约束的增删改

    • 增加

      • 添加外键约束: alter table 从表 add constraint 约束名称 foreign key 从表(外键字段) references 主表(主键字段);
      • 添加主键约束: alter table 表 add constraint 约束名称 primary key 表(主键字段);
      • 添加唯一性约束: alter table 表 add constraint 约束名称 unique 表(字段);
    • 删除

      • 删除外键约束: alter table 表名 drop foreign key 外键(区分大小写) ;
      • 删除主键约束: alter table 表名 drop primary key ;
      • 删除约束约束: alter table 表名 drop key 约束名称 ;
    • 修改

      • mysql 对有些约束的修改时不支持,所以我们可以先删除,再添加
 【案例】:向t_student表中添加约束
 alter table t_student add constraint fk_classes_id_1 foreign key(classes_id) references t_classes(classes_id);
 alter table t_student add constraint pk primary key(student_id);
 alter table t_student add constraint uk unique(email);
 ​
 【案例】:去除t_student表中的外键、主键、约束的约束
 alter table t_student drop foreign key classno;
 alter table t_student drop primary key no;
 alter table t drop key foreign key;
 ​
 【案例】:修改t_student中的约束
 alter table t_student modify student_name varchar(30) unique;

\