1.show 命令
基本命令 | 说明 |
show status; | 查看服务器状态 |
show create database 数据库名; | 显示建库语句 |
show create table 表名; | 显示建表语句 |
show grants; | 显示用户权限 |
show errors; | 显示服务器错误信息 |
show warnings; | 显示服务器警告信息 |
2.数据库表操作
2.1创建表
要素:表名 表字段名 定义每个表字段
语法:create table table_name (column_name column_type);
例子:
- create table student(
- id int auto_increment,
- name varchar(64) not null,
- primary key(id)
- )engine = InnoDB default charset = utf8
- 字段可以设置为不为空,即not null;
- auto_increment 定义列为自增的属性,一般用于主键,数值会自动加1;
- primary key 关键字用于定义列为主键。 可以使用多列来定义主键,列间以逗号分隔。
- engine 设置存储引擎,charset 设置编码。此句可不写。
desc 表名;来查看表结构
2.2修改、删除表
2.2.1 修改字段属性
-
语法:
alter table 表名 modify 字段 字段属性
-
alter table** student **modify** nume char not null;
2.2.2增加字段
- 语法:
alter table 表名 add 字段 字段属性 (after 字段);
alter table student add score float ;
alter table student add score float ;
2.2.3修改字段名
-
语法:
alter table 表名 change 原字段名 新字段名 新字段属性;
-
alter table student change score level double;
2.2.4重命名表名
-
alter table 原表名 rename 新表名;
-
alter table student rename students;
2.3插入数据
语法:
- 插入一条数据:
insert into table_name ( 字段1, 字段2,...字段N ) values
( value1, value2,...valueN );
- insert into table_name values ( value1, value2,...valueN );
- 插入多条数据,用’,‘隔开:
insert into table_name values
( value1, value2,...valueN ),
( value1, value2,...valueN ),
( value1, value2,...valueN );
3.数据操作
3.1 查询
3.1.1基础查询
语法 | 说明 |
select * from 表名; | 查看表中所有数据 |
select 字段1,字段名2 ... from 表名; | 查看表中字段1,字段2 … 中的数据 |
select distinct 字段 from 表名; | 去重查询 |
3.1.2限制查询
语法 | 说明 |
select 字段列表 from 表名 limit n; | 返回字段的n条数据,n>=0 |
select 字段列表 as 别名 from 表名 limit n; | 返回字段的n条数据,并把字段修改为其他的名字 |
select 字段列表 from 表名 limit n,m; | 返回第n条数据后的m条数据 |
select 字段列表 from 表名 limit n offset m; | 从 第m条数据后返回n个数据,可用于实现分页 |
3.1.3条件查询
语法:select 字段名列表 from 表名 where条件
关系运算符:> 、 >=、 <、 <=、 =、!=、<>、 between… and
逻辑运算符:and 、 or、 not
集合运算符:in 、not in
判空运算符:is null、is not null
通配符:_、%(与关键字一起使用)
3.1.4排序查询
语法:
select 字段列表 from 表名 order by 字段 (asc);
默认升序select 字段列表 from 表名 order by 字段 desc;
降序- 可与limit、条件等方式连用
3.2集合函数
函数 | 说明 | eg |
count() | 返回列的函数 | select count(字段) from 表名; 字段为*或者1时计算结果包括空值 |
sum() | 返回列的和 | select sum(字段) from 表名; |
avg() | 返回列的均值 | select avg(字段) from 表名; |
max() | 返回列的最大值 | select max(字段) from 表名; |
min() | 返回列的最小值 | select min(字段) from 表名; |
3.3分组查询
select 字段名列表(包含集合函数)from 表名 group by 字段;
select 字段名列表(包含集合函数)from 表名 group by 字段 having 条件;
3.4数据修改
语法:
update 表名 set 字段1 = 值1,字段2=值2... where 条件
- 不加where是修改所有数据
- 客户端启动时可加上参数:
mysql -u root --safe-updates -p
如果数据更新不加where会报错
3.5数据删除
delete命令
delete from 表名 where 条件;
- 不加条件会删除表中所有数据
truncate命令
truncate table 表名;
- 清空表中所有记录,相当于
delete from 表名;