mysql数据库常用的操作语句总结
一、数据库进行操作(database)
操作语句 | 执行的操作 |
---|
create database 数据库名称[库选项] | 创建数据库 |
show databases | 查看所有数据库 |
show create database 数据库名称 | 查看指定数据库的创建信息 |
use 数据库名称 | 选择数据库 |
mysql -u 用户名 -p 数据库名 | 登录mysql服务器选择数据库 |
drop database 数据库名称 | 删除数据库 |
二、数据表操作
操作语句 | 执行的操作 |
---|
create [temporary] table [if not exists] 表名 (字段名 字段类型 [字段属性]…)[表选项] | 创建数据表 字段名:表的列名 字段类型:数据类型 字段属性:某些约束个条件 |
show tables [like 匹配模式] | 查看数据表 |
show table status [from 数据库名] [like 匹配模式] | 查看数据库中表的状态 |
alter table 旧表名 rename 新表名 | 修改单个数据表名称 |
rename 旧表名1 to 新表名1 [, 旧表名2 to 新表名2] | 修改多个数据表名称 |
alter table 表名 表选项 [=] 值 | 修改表选项 |
describe/desc 数据表名 [字段名] | 查看表结构 |
show create table 表名 | 能看到创建表时的sql语句和字符编码 |
show [full] columns from 数据表 [from 数据库] | 查看完整数据 full可以查看注释等 |
alter table 表名 change [colunm] 旧字段名 新字段名 字段类型 [字段属性] | 修改表结构 |
alter table 表名 modify [column] 字段名 新类型 [字段属性] | 修改单列属性 |
alter table 表名 drop [column] 字段名 | 将某个字段从数据表删除 |
drop table [if exists] 表1[,表2 …] | 删除 |
三、表的字段约束
标识符 | 约束 |
---|
unsigned | 无符号(正数) |
zerofill | 前导零填充 |
auto_increment | 自增 |
default | 默认值 |
not null | 非空 |
PRIMARY KEY | 主键 (非null并不重复) |
unique | 唯一性 (可以为null但不重复) |
index | 常规索引 |
四、修改表结构
- 在表最后追加一个字段设置约束 alter table [表名] add [字段名] int not null;
- 在表的字段后面添加一个字段 alter table [表名] add [新字段] int not null after [老字段];
- 在表的最前面添加一个字段 alter table [表名] add [字段名] int first;
- 删除表中字段 alter table [表名] drop [字段名]
- 修改字段 alter table 表名 change[modify] 被修改后的字段信息 (change可以修改字段名, modify 不修改)
- 在表中的字段添加唯一性索引 alter table [表名] add unique [索引名] (字段名);
- 在表中的字段添加普通索引 alter table [表名] add index [索引名] (字段名);
- 将表中索引删除 alter table [表名] drop index [索引名] ;
- 更改表名称:alter table[旧表名] rename as [新表名]
- 更改auto_increment初始值 alter table [表名] auto_increment=[值]
- 更改表类型 alter table [表名] engine=[innodb]
五、查询数据
select [字段名] * from [表名] <where [条件] group by[分组字段] order by [排序] limit [分页参数]