#进阶六:连接查询
/*
多表查询
按功能分类:
内连接:
等值连接
非等值连接
自连接
外连接
左连接
右连接
全外连接
交叉连接
*/
USE girls;
SELECT * FROM admin;
SELECT * FROM beauty;
SELECT * FROM boys;
SELECT NAME,boyName FROM beauty,boys WHERE boyfriend_id = boys.`id`;
#sql192标准
/*
多表连接的结果为多表的交集部分
*/
#1.等值连接
#案例1:查询员工名和对应的部门名
SELECT
last_name,
department_name
FROM
employees e,
departments d
WHERE e.`department_id` = d.`department_id` #可以加筛选条件
#可以加分组
#案例1:查询每个城市的部门个数
SELECT
city,
COUNT(*) 个数
FROM
departments d,
locations l
WHERE d.`location_id` = l.`location_id`
GROUP BY city ;
SELECT COUNT(DISTINCT city) FROM locations;
SELECT COUNT(*) FROM locations;
#案例2:查询有奖金的每个部门的部门名和部门的领导编号和该部门的最低工资
SELECT
department_name,
d.manager_id,
MIN(salary)
FROM
employees e,
departments d
WHERE e.`department_id` = d.`department_id`
AND e.`commission_pct` IS NOT NULL
GROUP BY department_name;
#加排序
#案例:查询每个工种的工种名和员工的个数,并按员工的个数降序排序
SELECT job_title,COUNT(*) 员工个数 FROM employees e,jobs j WHERE e.`job_id`=j.`job_id` GROUP BY job_title ORDER BY 员工个数 DESC;
#可以实现三表连接?
#案例:查询员工名、部门名和所在的城市
SELECT
last_name,
department_name,
city
FROM
employees e,
departments d,
locations l
WHERE e.`department_id` = d.`department_id`
AND d.`location_id` = l.`location_id` ;
#创建工资级别表
USE myemployees;
CREATE TABLE job_grades
(grade_level VARCHAR(3),
lowest_sal INT,
highest_sal INT);
INSERT INTO job_grades
VALUES('A',1000,2999);
INSERT INTO job_grades
VALUES('B',3000,5999);
INSERT INTO job_grades
VALUES('C',6000,9999);
INSERT INTO job_grades
VALUES('D',10000,14999);
INSERT INTO job_grades
VALUES('E',15000,24999);
INSERT INTO job_grades
VALUES('F',25000,40000);
#2.非等值连接
#案例:查询员工的工资和工资级别
SELECT
SALARY,
grade_level
FROM
employees e,
job_grades j
WHERE salary BETWEEN lowest_sal
AND highest_sal ORDER BY grade_level;
#3.自连接(将一个表看成两种表连接)
#案例:查询员工名和上级的名称
SELECT last_name,employee_id,manager_id FROM employees;
SELECT e.last_name,e.`manager_id`,m.`employee_id`,m.`last_name` FROM employees e,employees m WHERE e.`manager_id` = m.`employee_id`;
#练习1:查询每个国家下的部门个数大于2的国家编号
SELECT country_id,COUNT(*) 部门个数 FROM locations l,departments d WHERE d.`location_id`=l.`location_id` GROUP BY country_id HAVING 部门个数>2;