MySQL 基础+高级篇- 数据库 -sql -尚硅谷 50-72篇笔记

明天可能会暂停更新,得把考试的一些东西,再搞一点

/*
分组函数
sum(),avg(),max(),min(),count()
分组查询
语法:
select 分组函数,列(要求出现在group by后面)
from 表
group by 分组的列表
*/
SELECT MAX(`salary`)FROM `employees`;
SELECT MAX(salary),job_id FROM `employees`
GROUP BY `job_id`;
SELECT AVG(salary),department_id
FROM employees
WHERE `email` LIKE '%a%'
GROUP BY `department_id`;

SELECT `department_id`,COUNT(`department_id`) 
FROM `employees`
GROUP BY `department_id`
HAVING COUNT(`department_id`)>2;

SELECT `job_id`,MAX(salary) FROM 
`employees` WHERE `commission_pct` IS NOT NULL
GROUP BY `job_id` HAVING MAX(salary)>12000;

SELECT `manager_id`,MIN(`salary`) FROM `employees`
WHERE `manager_id`>102
GROUP BY `manager_id`
HAVING MIN(salary)>5000;
# 分组前筛选用where 分组后筛选用having
# 分组函数只能在having语句中应用
SELECT last_name,LENGTH(last_name),COUNT(last_name)AS c FROM
`employees` 
GROUP BY LENGTH(`last_name`)
HAVING c>5;
# 分组查询多个字段
SELECT AVG(salary),`department_id`,`job_id`
FROM `employees` 
GROUP BY `department_id`,`job_id`;
# 分组也支持排序,可以对分组后的进行排序
SELECT 
  job_id,
  MAX(`salary`),
  MIN(`salary`),
  AVG(`salary`),
  SUM(`salary`)
FROM 
`employees`
GROUP BY job_id
ORDER BY job_id;
USE girls;
/*
连接查询
含义:又称多表查询
笛卡尔乘积:一张表中的一个记录和另一张表都有连接
sql92:
分类:
     内连接:
     等值连接
     非等值连接
     自连接
     外连接:
     左外连接
     右外连接
     全外连接
     交叉连接
 
如果为表起了别名,查询的时候要用别名           
*/
SELECT a.name,b.boyName FROM `beauty` AS a,`boys` AS b
WHERE a.`boyfriend_id`=b.`id`;
# 查询每个城市的部门个数
SELECT COUNT(*) AS 部门个数,b.`city` FROM `departments` a,
`locations` b
WHERE a.`location_id`=b.`location_id`
GROUP BY b.`city`;

#查询有奖金的每个部门的部门名和部门的领导编号和该部门的最低工资
SELECT 
a.`department_name`,
a.`manager_id`,
MIN(b.`salary`)
FROM
  `departments` AS a,
  `employees` AS b 
WHERE
a.`department_id`=b.`department_id`
AND b.`commission_pct` IS NOT NULL
GROUP BY a.`department_name`;
  
SELECT 
b.job_title,COUNT(*)
FROM 
`employees` AS a,
`jobs` AS b
WHERE 
a.`job_id`=b.`job_id`
GROUP BY b.`job_title`
ORDER BY COUNT(*) DESC;
/*
等值连接
1:多表等职连接的结果为多表交集部分
2:N表连接至少需要n-1个连接条件
3:多表的连接,顺序没有要求
*/

你可能感兴趣的:(数据库学习笔记)