- 显示数据库
- show databases;
- 创建数据库
- create database 数据库名称;
- 使用数据库
- use 数据库名称;
- 删除数据库
- drop database 数据库名称;
- 显示数据库表
- show tables;
- 创建表
- create table 表名(字段名1 数据类型 约束条件,字段名2 数据类型 约束条件,...);
- 删除表
- drop table 表名;
- 修改表的名字
- alter table 旧名字 rename 新名字;
- 查看字段信息、属性信息
- 字段和数据类型
- show columns from 表名;
- show full columns from 表名;
- desc 表名;
- 约束条件
- show index from 表名;
- 字段和数据类型
- 添加新的字段
- alter table 表名 add 新字段名 数据类型 约束条件;
- 删除字段
- alter table 表名 drop 字段名;
- 修改字段名字
- alter table 表名 change 旧字段名 新字段名 数据类型 约束条件;
- 修改字段的数据类型
- alter table 表名 modify 字段名 新数据类型 约束条件;
- 约束条件的修改
- 添加和删除主键(一个表中只能有一个主键,否则会报错)
- 添加主键
- alter table 表名 add primary key(字段名);
- alter table 表名 modify 字段名 数据类型 primary key;
- alter table 表名 change 字段名 字段名 数据类型 primary key;
- 删除主键
- alter table 表名 drop primary key;
- 添加主键
- 添加和删除unique
- 添加unique
- alter table 表名 add unique(字段名);
- alter table 表名 modify 字段名 数据类型 unique;
- alter table 表名 change 字段名 字段名 数据类型 primary key;
- 删除unique
- alter table 表名 drop index 字段名;
- 添加unique
- 添加和删除非空约束
- 添加非空约束
- alter table 表名 modify 字段名 数据类型 not null;
- alter table 表名 change 字段名 字段名 数据类型 not null;
- 删除非空约束
- alter table 表名 modify 字段名 数据类型 null;
- alter table 表名 modify 字段名 数据类型;
- alter table 表名 change 字段名 字段名 数据类型 null;
- alter table 表名 change 字段名 字段名 数据类型;
- 添加非空约束
- 添加和删除默认值
- 添加默认值约束
- alter table 表名 modify 字段名 数据类型 default 默认值;
- alter table 表名 change 字段名 字段名 数据类型 default 默认值;
- 删除默认值约束
- alter table 表名 modify 字段名 数据类型;
- alter table 表名 change 字段名 字段名 数据类型;
- 添加默认值约束
- 添加和删除自增约束
- 添加自增约束 (只针对key值字段添加:主键 外键 唯一约束的字段)(添加成功后默认不能为空)
- alter table 表名 modify 字段名 数据类型 auto_increment;
- alter table 表名 change 字段名 字段名 数据类型 auto_increment;
- 修改自增约束的初始值为n
- alter table 表名 auto_increment = n;
- 删除自增约束
- alter table 表名 modify 字段名 数据类型;
- alter table 表名 change 字段名 字段名 数据类型;
- 添加自增约束 (只针对key值字段添加:主键 外键 唯一约束的字段)(添加成功后默认不能为空)
- 添加和删除外键
- 添加外键
- alter table 表名 add foreign key(外键字段) references 主表名(主表字段); //默认外键名和字段名相同
- alter table 表名 add constraint 外键名 foreign key(外键字段) references 主表名(主表字段);
- 删除外键
- alter table 表名 drop foreign key 外键名;
- 添加外键
- 插入记录
- insert into 表名 (字段名,1,字段名2,...)values (数据1,数据2,...);
- 更新记录
- update 表名 set 更新字段名 = 数据 where 可确定记录的字段名 = 对应值;
- 显示记录
- select 字段1,字段2,字段3,... from 表名; //显示一部分字段信息
- select * from 表名; //显示所有记录信息
- select * from 表名 where 字段 = 数据; //显示指定的某条记录
- select 字段名 from 表名 where 字段 = 数据; // 显示某条记录的某个字段数据
- 删除一条记录
- delete from 表名 where 字段名 = 具体数据;
- 添加和删除主键(一个表中只能有一个主键,否则会报错)
- 显示auto_increment参数
- show variables like '%auto_inc%';
- set @@auto_increment_increment = 5; //修改自增初始值为5
- set auto_increment_increment =5; //修改自增初始值为5
- set auto_increment_offset =2; // 修改步长为2
- set @@auto_increment_offset =2; // 修改步长为2