创建
如果我们要创建一个用户表,我们可以写如下代码
create table tb_user (
id int comment 'ID',
username varchar(20) comment '用户名',
name varchar(10) comment '姓名',
age int comment '年龄',
gender char(1) comment '性别'
) comment '用户表';
约束:用来限制储存表中的数据,我们约束的目的是为了保证数据中数据的正确,有效性和完整性
约束的分类:
通过上面的约束可以对我们的代码进行加工
create table tb_user2 ( id int primary key auto_increment comment 'ID', username varchar(20) not null unique comment '用户名', name varchar(10) not null comment '姓名', age int comment '年龄', gender char(1) default '男' comment '性别' ) comment '用户表';
数据类型:
MySQL中数据主要可以分成三类:数值类型,字符串类型,日期类型
数值类型我们主要了解的是下面几个:
tinyint 小整数值
int/integer 大整数值
字符串类型我们主要了解下面几个:
char 指定长度字符串
varchar 指定大小内长度字符串
日期时间类型我们主要了解下面这个:
datetime 混合日期和时间
查询
- 查询当前数据库所有表 show tables;
- 查看指定表结构 desc 表名 ;
- 查询指定表的建表语句 show create table 表名 ;
修改
- 添加字段 alter table 表名 add 字段名 类型 (长度) [ comment 注释 ] [ 约束 ];
- 修改数据类型 alter table 表名 modify 字段名 新数据类型 (长度);
- 修改字段名和字段类型 alter table 表名 change 旧字段名 新字段名 类型 (长度) [ comment 注释 ] [ 约束 ];
- 删除字段 alter table 表名 drop 字段名;
- 修改表名 rename table 表名 to 新表名;
删除
- 删除表 drop table [ if exists ] 表名;
- 删除指定表,并重新创建表 truncate table 表名;