分组查询语法:select 分组字段,聚合函数,group_contact(查看类型), from 表名 [where查询条件] [group by 分组字段][order by 排序字段 asc/desc] [limit 分页条件];
1、按照学历分组,查询每个班分别有多少个人
- SELECT
- class_name,
- COUNT(*)
- FROM
- student_info
- GROUP BY class_name;
2、group_concat协助查看详细,
- SELECT
- education_level,
- COUNT(*),
- GROUP_CONCAT(stu_name)
- FROM
- student_info
- GROUP BY education_level;
3、多字段分组:分组之后,针对相同数据,再次分组
- SELECT
- class_name,
- gender,
- COUNT(*),
- GROUP_CONCAT(stu_name)
- FROM
- student_info
- GROUP BY class_name,
- gender;
- SELECT
- class_name,
- gender,
- AVG(IFNULL(age,0)),
- GROUP_CONCAT(age)
- FROM
- student_info
- GROUP BY class_name,
- gender;
4、having:针对聚合过后的内容再次过滤
查询平均年龄大于20岁的班是哪些
- SELECT
- class_name,
- gender,
- AVG(IFNULL(age,0)) AS a,
- GROUP_CONCAT(age)
- FROM
- student_info
- GROUP BY class_name,
- gender
- HAVING a >=20;
5、sql执行顺序:from>where>group>having>select>distint
6、多表联合查询
笛卡尔乘积:把所有的情况罗列出来
inner join:内连接查询,查询两表相交的部分
inner join 具体语法:
- select*from左表 inner join 右表 on 左表的外键=右表的主键;
- select*from左表,右表where左表的外键=右表的主键;
举例:
- SELECT
- a.*,
- d.
dept_name
- FROM
- admin_info AS a
- INNER JOIN dept_info AS d
- ON a.
fk_dept_id
= d.id;
- SELECT
- *
- FROM
- admin_info AS a,
- dept_info AS d
- WHERE a.fk_dept_id = d.id;
外联查:左外联查,右外联查
基本语法:
- select*from左表 left [outer] join 右表 on 左表的外键=右表的主键;
- select*from左表 right [outer] join 右表 on 左表的外键=右表的主键;
例子:查询管理员的部门,有就显示,没有就显示null
- SELECT
- *
- FROM
- admin_info AS a
- LEFT JOIN dept_info AS d
- ON a.
fk_dept_id
= d.id;
例子:查询部门下的管理员,有就显示,没有就显示null
技巧:左表对应外键,右表对应主键
自关联:自己关联自己,例如地区表和菜单表
1、查询中国下有哪些省份:(父表用主键id子表用pid)
- SELECT
- s.*,
- g.
area_name
- FROM
- area_info AS s
- LEFT JOIN area_info AS g
- ON s.
pid
= g.id
- WHERE g.area_name =’中华人民共和国’;
2、查询广东省有哪些区
SELECT q.*,c.area_name
,s.area_name
FROM area_info AS q LEFT JOIN area_info AS c ON q.pid
= c.id
LEFT JOIN area_info AS s ON c.pid = s.id
WHERE s.area_name
= ‘广东省’;
3、查询比大王年龄大的人(本表比较,分析用inner)
- SELECT
- s2.*,
- s1.
age
AS ‘大王的年龄’ - FROM
- student_info AS s1
- INNER JOIN student_info AS s2
- WHERE s1.
age
< s2.age
- AND s1.
stu_name
=’大王’;
子查询:一个查询中被嵌套了其他的查询语句,那么其他的查询语句就是子查询!子查询的返回结果只能是单行单列
查询管理员以及对应的部门
- SELECT
- id,
- admin_name,
- age,
- (SELECT
- dept_name
- FROM
- dept_info
- WHERE id = fk_dept_id) AS dept_name
- FROM
- admin_info;
in 和 exists的区别
in用于子查询数据量较少的情况
exists用于子表数据量多的情况
DCL:数据库控制语言
创建账号并且授权:
- grant 权限名1,权限名2,权限名3…… on 数据库的名称.表的名称 to ‘用户名’@’允许登录的IP地址’[identified by’密码’];
举例:
- grant all on test.* to ‘laopu’@’%’ identified by’123465’;
- flush privileges;//刷新权限
可以使用laopu 123465 去登录MySQL数据库!
语法具体:
(1)、权限名 上面图片的英文单词 all 代表所有权限
(2)、test.* 针对test库的所有表
(3)、’laopu’@’%’ laopu 是账号,%代表是所有IP地址 也可以写特定的IP地址
(4)、identified by ‘密码’ 给laopu 账号,设置密码
三、移除某些权限
移除权限:revoke
revoke 权限名1,权限名2,权限名3…… on 数据库名称.表的名称 from ‘用户名’@’允许登录的IP地址’;
举例:
revoke insert,update,delete on test.* from ‘laopu’@’%’;flush privileges; //刷新权限