MySQL随记 - 连接查询

Posted HQ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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没有的·

以上是关于MySQL随记 - 连接查询的主要内容,如果未能解决你的问题,请参考以下文章

MySQL随记 - 子查询

MySQL随记

Oracle随记

python 随记

连接MySQL出现错误:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)(代码片段

部分代码片段