1.DDL-数据库操作
show databases;
create database 数据库名;
use 数据库名;
select database();
drop database 数据库名;
2.DDL-表操作
show tables;
create table 表名(字段 字段类型,字段 字段类型);
desc 表名;
show create table 表名;
alter table 表名 add/modify/change/drop/rename to;
drop table 表名;
3.DML数据操纵操作
insert into 表名 (字段1,字段2...) value (值1,值2); #增
update 表名 set 字段1=值1,字段2=值2 where 条件; #改
delete from 表名 where 条件; #删
4.DQL查询操作
1.查询多个字段
select 字段1,字段2,字段3... from 表名;
select * from 表名;
2.设置别名
select 字段1[as 别名1],字段2[别名2]... from 表名;
3.去除重复记录
select distinct 字段列表 from 表名;
4.条件查询
select 字段列表 from 表名 where 条件列表;
select * from emp where name like '__';#模糊匹配 一个下划线代表一个字符
5.聚合函数
将一列数据作为一个整体,进行纵向计算。
count #统计数量
max #最大值
min #最小值
avg #平均值
sum #求和
select 聚合函数(字段列表) from 表名;
6.分组查询
select 字段列表 from 表名 [where 条件] group by 分组字段名 [having 分组后过滤条件];
执行顺序:where > 聚合函数 >having
分组之后,查询的字段一般为聚合函数和分组字段,查询其他字段无任何意义。
7.排序查询
select 字段列表 from 表名 order by 字段 排序方式;
ASC:升序
DESC:降序
8.分页查询
select 字段列表 from 表名 limit 起始索引,查询记录数;
*起始索引从0开始,起始索引=(查询页码-1)每页显示记录数
分页查询是数据库的方言,不同数据库有不同的实现,mysql中是limit
如果查询的是第一页数据,起始索引可以省略,直接简写为limit 10
9.DQL语句练习
查询年龄为20,21,22,23岁的女性员工信息。
select * from emp where gender ='女' and age in(20,21,22,23);
查询性别为男,并且年龄再20-40岁(含)以内的姓名为三个字的员工。
select * from emp where gender ='男' and age between 20 and 40 name like'___';
统计员工表中,年龄小于60岁的,男性员工和女性员工的人数。
select gender,count(*) from emp where age<60 group by gender;
查询所有年龄小于等于35岁员工的姓名和年龄,并对查询结果按年龄升序排列,如果年龄相同按入职时间降序排列。
select name, age from emp where age<=35 order by age asc,entrydate desc;
查询性别为男,且年龄在20-40岁(含)以内的前5个员工信息,对查询的结果按年龄升序排序,年龄相同按入职实践升序排序。
select * from emp where gender='男',and age between 20 and 40 order by age asc,entryday asc limit 5 ;
10.小结
select - from - where - group by - having - order by - limit #编写顺序
from - where - group by - having -select - order by - limit #执行顺序
5.DCL数据控制操作
1.查询用户
use mysql;
select *from user;
2.创建用户
create user '用户名'@'主机名' identified by '密码'; #通配符%表示任意主机
3.修改用户密码
alter user '用户名'@'主机名' identified with mysql_native_password by '新密码';
4.删除用户
drop user '用户名'@'主机名';
5.查询权限
show grants for '用户名'@'主机名';
6.授予权限
grant 权限列表 on 数据库名.表名 to '用户名'@'主机名';
7.撤销权限
revoke 权限列表 on 数据库名.表名 from '用户名'@'主机名';