1 概述

table
设计:尽量遵循 '第三范式 3NF'
存储数据
命名:字母,数字、'_'、'$' 组成
长度:一般不超过 30 个字符

2 语法

2.1 创建 create table

create table student_info (
  sno         int unsigned auto_increment comment '学号',
  name        varchar(50) not null comment '姓名',
  create_date date not null comment '创建时间',
  primary key(sno)
) engine=innodb default charset=utf8 comment '学生信息表';

参数解析:

1. 主键相关
   (1) unsigned auto_increment: 从 1 自增,常用于主键
   (2) primary key: 定义主键

2. 默认设置 -- 一般无需显示设置,默认即可
   (1) engine=innodb存储引擎(默认 innodb-- show engines;
   (2) default charset=utf8:字符编码(默认 utf8)
       -- show variables like 'character_set_%';
/*
3. 说明:一般创建表时,均要添加以下字段
   create_user varchar(50) not null comment '创建人',
   create_date date not null comment '创建时间',
   update_user varchar(50) not null comment '更新人',
   update_date date not null comment '更新时间'*/

2.2 修改 alter table

-- '增加' 一列或者多列
alter table student_info add sex varchar(10) comment '性别';
alter table student_info add (id_type varchar(10) comment '证件类型', 
                              id_no int comment '证件号码');
---- 按指定位置添加列 before | after
alter table student_info add age int comment '年龄' after sex;
    
-- '修改' 一列或者多列
---- 数据类型
alter table student_info modify sex varchar(20) not null;
---- 列名
alter table student_info rename column sex to new_sex;
---- 表名
alter table student_info rename to new_student_info ;
alter table new_student_info rename to student_info;   

2.3 清空 truncate table

-- 仅清空表数据
truncate table student_info;

2.4 删除 drop table

-- 删除表结构
drop table student_info;

3 扩展

3.1 查询表、列、备注

-- 查询表
select t.table_schema,
       t.table_name,
       t.table_comment
  from information_schema.tables t
 where t.table_name = 'student_info';
 
-- 查询列
select c.table_schema,
       c.ordinal_position,
       c.column_name,
       c.column_type,
       c.column_comment
  from information_schema.columns c
 where c.table_name = 'student_info'
 order by c.ordinal_position;

3.2 Mysql 外键详解(Foreign Key)

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐