欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

7、MySQL数据库-连接查询

程序员文章站 2022-05-08 14:53:55
...

七、连接查询

1.sql92

1.1 等值连接
1.查询女神名和对应的男神名
select NAME,boyName 
from boys,beauty 
where beauty.boyfriend_id = boys.id;

2.为表起别名-查询员工名、工作岗位号、工作岗位名
select e.last_name,e.job_id,job_title 
from employees e,jobs j 
where e.job_id=j.job_id;

3.两个表的顺序调换-查询员工名、岗位号、工种名
select e.last_name,e.job_id,job_title 
from jobs j,employees e 
where e.job_id=j.job_id;

4.加筛选-查询城市名中第二个字符为o的部门名和城市名
select department_name,city 
from departments d,location l 
where d.location_id = l.location_id 
and city like '_o%';

5.实现三表连接-查询员工名、部门名和所在的城市以S开头的
select last_name,department_name,city 
from employees e,departments d,location l 
where e.department_id=d.department_id and d.location_id=l.location_id and city like 's%';
1.2自连接
1.查询员工名和上级的名称
select e.employee_id,e.last_name,m.employee_id,last_name 
from employee e,employee m
where e.manager_id=m.manager_id;

2.sql99

7、MySQL数据库-连接查询

2.1内连接-等值连接
1.查询员工名和部门名
SELECT last_name,department_name
FROM departments d,employees e  
WHERE e.department_id =d.department_id;

2.加筛选条件-1)查询部门编号>100的部门名和所在的城市名
SELECT department_name,city
FROM departments d
JOIN locations l
ON d.`location_id` = l.`location_id`
WHERE d.`department_id`>100;

3.加筛选条件-2)查询名字中包含E的员工名和工作岗位名
SELECT last_name,job_title
FROM employees e
JOIN jobs j
ON e.`job_id`=j.`job_id`
WHERE e.`last_name` LIKE '%e%';

4.添加分组+筛选-查询每个城市的部门个数
SELECT COUNT(*) 部门个数,l.`city`
FROM departments d
JOIN locations l
ON d.`location_id`=l.`location_id`
GROUP BY l.`city`;

5.添加分组+筛选+排序-查询每个部门中员工个数>10的部门名,并按员工个数降序
SELECT COUNT(*) 员工个数,d.department_name
FROM employees e
JOIN departments d
ON e.`department_id`=d.`department_id`
GROUP BY d.`department_id`
HAVING 员工个数>10
ORDER BY 员工个数 DESC;

6.添加多表查询-查询员工名、部门名、工作岗位名,并按部门名降序
SELECT last_name,department_name,job_title
FROM employees e
JOIN departments d ON e.`department_id`=d.`department_id`
JOIN jobs j ON e.`job_id`=j.`job_id`
ORDER BY department_name DESC;
2.2内连接-非等值连接
1.查询员工的工资级别
SELECT salary,grade_level
FROM employees e
JOIN job_grades g
ON e.`salary` BETWEEN g.`lowest_sal` AND g.`highest_sal`;

2.查询部门编号在10-90之间的员工的工资级别,并按级别进行分组
SELECT e.`salary`,g.`grade_level`,e.`department_id`
FROM employees e
JOIN job_grades g
ON e.`salary` BETWEEN g.`lowest_sal` AND g.`highest_sal`
WHERE e.`department_id` BETWEEN 10 AND 90
GROUP BY g.`grade_level`;

3.查询每个工资级别的个数>20的个数,并且按工资级别降序
SELECT COUNT(*),grade_level
FROM employees e
JOIN job_grades g
ON e.`salary` BETWEEN g.`lowest_sal` AND g.`highest_sal`
GROUP BY grade_level
HAVING COUNT(*)>20
ORDER BY grade_level DESC
2.3内连接-自连接
1.查询员工名和对应的领导名
SELECT e.`last_name`,m.`last_name`
FROM employees e
JOIN employees m
ON e.`manager_id`=m.`employee_id`;

2.查询姓名中含有字符K的员工名和对应的领导名
SELECT e.`last_name`,m.`last_name`
FROM employees e
JOIN employees m
ON e.`manager_id`=m.`employee_id`
WHERE e.last_name LIKE '%K%';