MySQL随记 - 连接查询

一、连接分类

1. 内连接
	(1)等值连接
	(2)非等值连接
	(3)自连接
2. 外连接
	(1)左外连接
	(2)右外连接
	(3)全外连接
3. 交叉连接

二、外连接

# 等值连接
# 案例1:查询员工名对应的部门名
SELECT last_name, department_name
FROM employees, departments
WHERE employees.`department_id` = departments.`department_id`;

# 案例2:查询有奖金的员工名、部门名
SELECT last_name, department_name, commission_pct
FROM employees AS e, departments AS d
WHERE e.`department_id` = d.`department_id`
AND commission_pct IS NOT NULL;

# 案例3:查询城市名中第二个字符为o的部门名和城市名
SELECT department_name, city
FROM departments AS d, locations AS l
WHERE d.`location_id` = l.`location_id`
AND city LIKE '_o%';

# 案例4:查询每个城市的部门个数
SELECT COUNT(*), city, department_name
FROM departments AS d, locations AS l
WHERE d.`location_id` = l.`location_id`
GROUP BY city;

# 案例5:查询有奖金的每个部门名和部门的领导编号和该部门的最低工资
SELECT department_name, d.manager_id,MIN(salary)
FROM departments AS d, employees AS e
WHERE d.`department_id` = e.`department_id`
AND commission_pct IS NOT NULL
GROUP BY department_name, d.manager_id;

# 案例6;查询每个工种的工种名和员工的个数,并且按员工个数降序
SELECT job_title, COUNT(*)
FROM employees AS e, jobs AS j
WHERE e.`job_id` = j.`job_id`
GROUP BY job_title
ORDER BY COUNT(*) DESC;

# 案例7:查询员工名、部门名和所在城市
SELECT last_name, department_name, city
FROM departments AS d, employees AS e, locations AS l
WHERE d.`department_id` = e.`department_id` AND d.`location_id` = l.`location_id`;

三、外连接

应用场景:用于查询一个表中有,另一个表没有的记录
特点:
1.外连接的查询结果为主表中的所有记录
	如果从表中有和它匹配的,则显示匹配的值
	如果从表中没有和它匹配的,则显示null
	外连接查询结果=内连接结果+主表中有而从表没有的记录
2.左外连接,left join左边的是主表;右外连接,right join右边的是主表
3.左外和右外交换两个表的顺序,可以实现同样的结果
4.全外连接=内连接的结果+表1中有但表2没有的+表2中有表1没有的·
posted @ 2020-01-30 16:44  qi.hu  阅读(98)  评论(0编辑  收藏  举报