多表查询概述
- 多表查询,也称为关联查询,指两个或更多个表一起完成查询操作。
- 前提条件:这些一起查询的表之间是有关系的(一对一、一对多),它们之间一定是有关联字段,这个关联字段可能建立了外键,也可能没有建立外键。比如:员工表和部门表,这两个表依靠“部门编号”进行关联。
- 为什么不把多张表合成一张表?答:多张表合成一张表会导致很多信息的冗余!将不必要的冗余信息从磁盘导入内存将导致很多的磁盘IO。
1 一个案例引发的多表连接
1.1 案例说明
从多个表中获取数据:
#案例:查询员工的姓名及其部门名称 SELECT last_name, department_name FROM employees, departments;
查询结果(从上图可以看到:每个员工都与每个部门匹配了一遍,此错误称为笛卡尔积的错误):
# 2889行结果 +-----------+----------------------+ | last_name | department_name | +-----------+----------------------+ | King | Administration | | King | Marketing | | King | Purchasing | | King | Human Resources | | King | Shipping | | King | IT |
分析错误情况:
SELECT COUNT(employee_id) FROM employees; #输出107行 SELECT COUNT(department_id)FROM departments; #输出27行 SELECT 107*27 FROM dual; # 2889=107*27 ---—>错误由笛卡儿积导致
把上述多表查询中出现的问题称为:笛卡尔积的错误。错误的原因:缺少了多表的连接条件
1.2 笛卡尔积理解
笛卡尔乘积是一个数学运算。假设有两个集合 X 和 Y,那么 X 和 Y 的笛卡尔积就是 X 和 Y 的所有可能组合,也就是第一个对象来自于 X,第二个对象来自于 Y 的所有可能。组合的个数即为两个集合中元素个数的乘积数
SQL92中,笛卡尔积也称为 交叉连接 ,英文是 CROSS JOIN 。在 SQL99 中也是使用 CROSS JOIN表示交叉连接。它的作用就是可以把任意表进行连接,即使这两张表不相关。在MySQL中如下情况会出现笛卡尔积:
#查询员工姓名和所在部门名称 SELECT last_name,department_name FROM employees,departments; SELECT last_name,department_name FROM employees CROSS JOIN departments; SELECT last_name,department_name FROM employees INNER JOIN departments; SELECT last_name,department_name FROM employees JOIN departments;
笛卡尔积的错误会在下面条件下产生:
- 省略多个表的连接条件(或关联条件)
- 连接条件(或关联条件)无效
- 所有表中的所有行互相连接
为了避免笛卡尔积, 可以在 WHERE 加入有效的连接条件。
加入连接条件后,查询语法:
SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column1 = table2.column2; #连接条件
在 WHERE子句中写入连接条件。
正确写法:
#案例:查询员工的姓名及其部门名称 SELECT last_name, department_name FROM employees, departments WHERE employees.department_id = departments.department_id;
在表中有相同列时,在列名之前加上表名前缀。
演示代码
/*回顾 SELECT ...,....,.... FROM .... WHERE .... AND / OR / NOT.... ORDER BY .... (ASC/DESC),....,... LIMIT ...,... */ #1. 熟悉本教学中的几个表 DESC employees; /* +----------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------------+-------------+------+-----+---------+-------+ | employee_id | int(6) | NO | PRI | 0 | | | first_name | varchar(20) | YES | | NULL | | | last_name | varchar(25) | NO | | NULL | | | email | varchar(25) | NO | UNI | NULL | | | phone_number | varchar(20) | YES | | NULL | | | hire_date | date | NO | | NULL | | | job_id | varchar(10) | NO | MUL | NULL | | | salary | double(8,2) | YES | | NULL | | | commission_pct | double(2,2) | YES | | NULL | | | manager_id | int(6) | YES | MUL | NULL | | | department_id | int(4) | YES | MUL | NULL | | +----------------+-------------+------+-----+---------+-------+ */ DESC departments; /* +-----------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------------+-------------+------+-----+---------+-------+ | department_id | int(4) | NO | PRI | 0 | | | department_name | varchar(30) | NO | | NULL | | | manager_id | int(6) | YES | MUL | NULL | | | location_id | int(4) | YES | MUL | NULL | | +-----------------+-------------+------+-----+---------+-------+ */ DESC locations; /* +----------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------------+-------------+------+-----+---------+-------+ | location_id | int(4) | NO | PRI | 0 | | | street_address | varchar(40) | YES | | NULL | | | postal_code | varchar(12) | YES | | NULL | | | city | varchar(30) | NO | | NULL | | | state_province | varchar(25) | YES | | NULL | | | country_id | char(2) | YES | MUL | NULL | | +----------------+-------------+------+-----+---------+-------+ */ #查询员工名为'Abel'的人在哪个城市工作? #需要使用多表查询-->1\2\3步 SELECT * FROM employees WHERE last_name = 'Abel'; /*1.通过名字查到Abel的各字段信息,得知部门号为80 +-------------+------------+-----------+-------+--------------------+------------+--------+----------+----------------+------------+---------------+ | employee_id | first_name | last_name | email | phone_number | hire_date | job_id | salary | commission_pct | manager_id | department_id | +-------------+------------+-----------+-------+--------------------+------------+--------+----------+----------------+------------+---------------+ | 174 | Ellen | Abel | EABEL | 011.44.1644.429267 | 1996-05-11 | SA_REP | 11000.00 | 0.30 | 149 | 80 | +-------------+------------+-----------+-------+--------------------+------------+--------+----------+----------------+------------+---------------+ */ SELECT * FROM departments WHERE department_id = 80; /*2.通过部门号80得到部门信息,得知部门地址id为2500 +---------------+-----------------+------------+-------------+ | department_id | department_name | manager_id | location_id | +---------------+-----------------+------------+-------------+ | 80 | Sales | 145 | 2500 | +---------------+-----------------+------------+-------------+ */ SELECT * FROM locations WHERE location_id = 2500; /*3.显示部门地址id为2500的地址信息 +-------------+------------------------------------------+-------------+--------+----------------+------------+ | location_id | street_address | postal_code | city | state_province | country_id | +-------------+------------------------------------------+-------------+--------+----------------+------------+ | 2500 | Magdalen Centre, The Oxford Science Park | OX9 9ZB | Oxford | Oxford | UK | +-------------+------------------------------------------+-------------+--------+-------- */ #-->通过三次查询才得到答案! #2. 出现笛卡尔积的错误 #错误的原因:缺少了多表的连接条件 #错误的实现方式:每个员工都与每个部门匹配了一遍。 SELECT employee_id,department_name FROM employees,departments; /*#查询出2889条记录 +-------------+----------------------+ | employee_id | department_name | +-------------+----------------------+ | 100 | Administration | | 100 | Marketing | | 100 | Purchasing | | 100 | Human Resources | | 100 | Shipping | | 100 | IT | | 100 | Public Relations | | 100 | Sales | */ #错误的方式 SELECT employee_id,department_name FROM employees CROSS JOIN departments;#查询出2889条记录 SELECT * FROM employees; #107条记录 SELECT 2889 / 107 FROM DUAL; SELECT * FROM departments; # 27条记录 # 2889=107*27 #3. 多表查询的正确方式:需要有连接条件 SELECT employee_id,department_name FROM employees,departments #两个表的连接条件 WHERE employees.`department_id` = departments.department_id; #连接条件为employees.`department_id` = departments.department_id; /*输出106行(!=107是因为有一行部门id为null) +-------------+------------------+ | employee_id | department_name | +-------------+------------------+ | 200 | Administration | | 201 | Marketing | | 202 | Marketing | | 114 | Purchasing | | 115 | Purchasing | */ #4. 如果查询语句中出现了多个表中都存在的字段,则必须指明此字段所在的表。 #建议:从sql优化的角度,建议多表查询时,每个字段前都指明其所在的表。 #department_id来自表employees故要写为select employees.department_id SELECT employees.employee_id,departments.department_name, employees.department_id FROM employees,departments WHERE employees.`department_id` = departments.department_id; /*部分输出 +-------------+------------------+---------------+ | employee_id | department_name | department_id | +-------------+------------------+---------------+ | 200 | Administration | 10 | | 201 | Marketing | 20 | | 202 | Marketing | 20 | | 114 | Purchasing | 30 | | 115 | Purchasing | 30 | */ #5. 可以给表起别名,在SELECT和WHERE中使用表的别名。 #-->此做法可以提高sql语句的可读性、让代码变简短 SELECT emp.employee_id,dept.department_name,emp.department_id FROM employees emp,departments dept WHERE emp.`department_id` = dept.department_id; /* +-------------+------------------+---------------+ | employee_id | department_name | department_id | +-------------+------------------+---------------+ | 200 | Administration | 10 | | 201 | Marketing | 20 | | 202 | Marketing | 20 | */ #如果给表起了别名,一旦在SELECT或WHERE中使用表名的话,则必须使用表的别 #名,而不能再使用表的原名。 #如下的操作是错误的: SELECT emp.employee_id,departments.department_name, emp.department_id FROM employees emp,departments dept WHERE emp.`department_id` = departments.department_id; #6. 结论:如果有n个表实现多表的查询,则需要至少n-1个连接条件 #练习:查询员工的employee_id,last_name,department_name,city SELECT e.employee_id,e.last_name,d.department_name,l.city, e.department_id,l.location_id FROM employees e,departments d,locations l WHERE e.`department_id` = d.`department_id` AND d.`location_id` = l.`location_id`; /* +-------------+-------------+------------------+---------------------+---------------+-------------+ | employee_id | last_name | department_name | city | department_id | location_id | +-------------+-------------+------------------+---------------------+---------------+-------------+ | 200 | Whalen | Administration | Seattle | 10 | 1700 | | 201 | Hartstein | Marketing | Toronto | 20 | 1800 | | 202 | Fay | Marketing | Toronto | 20 | 1800 | */ /*学习或教学的两种方式 演绎式:提出问题1 ---> 解决问题1 ----> 提出问题2 ---> 解决问题2 .... 归纳式:总--分 */
2 多表查询分类讲解
2.1 等值连接 & 非等值连接
2.1.1 等值连接
SELECT employees.employee_id, employees.last_name, employees.department_id, departments.department_id, departments.location_id FROM employees, departments WHERE employees.department_id = departments.department_id;
拓展1:多个连接条件与 AND 操作符
拓展2:区分重复的列名
- 多个表中有相同列时,必须在列名之前加上表名前缀。
- 在不同表中具有相同列名的列可以用 表名 加以区分。
SELECT employees.last_name, departments.department_name, employees.department_id FROM employees, departments WHERE employees.department_id = departments.department_id;
拓展3:表的别名
- 使用别名可以简化查询。
- 列名前使用表名前缀可以提高查询效率。
SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e , departments d WHERE e.department_id = d.department_id;
需要注意的是,如果使用了表的别名,在查询字段中、过滤条件中就只能使用别名进行代替,不能使用原有的表名,否则就会报错。
阿里开发规范:
【强制 】对于数据库中表记录的查询和变更,只要涉及多个表,都需要在列名前加表的别名(或表名)进行限定。
说明:对多表进行查询记录、更新记录、删除记录时,如果对操作列没有限定表的别名(或表名),并且操作列在多个表中存在时,就会抛异常。
正例 :select t1.name from table_first as t1 , table_second as t2 where t1.id=t2.id;
反例:在某业务中,由于多表关联查询语句没有加表的别名(或表名)的限制,正常运行两年后,最近在 某个表中增加一个同名字段,在预发布环境做数据库变更后,线上查询语句出现出 1052 异常:Column ‘name’ in field list is ambiguous。
拓展4:连接多个表
**总结:连接 n个表,至少需要n-1个连接条件。**比如,连接三个表,至少需要两个连接条件。
练习:查询出公司员工的 last_name,department_name, city
2.1.2 非等值连接
SELECT e.last_name, e.salary, j.grade_level FROM employees e, job_grades j WHERE e.salary BETWEEN j.lowest_sal AND j.highest_sal; /* +-------------+----------+-------------+ | last_name | salary | grade_level | +-------------+----------+-------------+ | King | 24000.00 | E | | Kochhar | 17000.00 | E | | De Haan | 17000.00 | E | | Hunold | 9000.00 | C | | Ernst | 6000.00 | C | | Austin | 4800.00 | B | | Pataballa | 4800.00 | B | | Lorentz | 4200.00 | B | | Greenberg | 12000.00 | D | | Faviet | 9000.00 | C | | Chen | 8200.00 | C | | Sciarra | 7700.00 | C | */
自连接 & 非自连接
当table1和table2本质上是同一张表,只是用取别名的方式虚拟成两张表以代表不同的意义。然后两个表再进行内连接,外连接等查询
题目:查询employees表,返回“Xxx works for Xxx”
SELECT CONCAT(worker.last_name ,' works for ' , manager.last_name) FROM employees worker, employees manager WHERE worker.manager_id = manager.employee_id ; /* +------------------------------------------------------------+ | CONCAT(worker.last_name ,' works for ', manager.last_name) | +------------------------------------------------------------+ | Kochhar works for King | | De Haan works for King | | Hunold works for De Haan | | Ernst works for Hunold | | Austin works for Hunold | | Pataballa works for Hunold | | Lorentz works for Hunold | | Greenberg works for Kochhar | */
练习:查询出last_name为 ‘Chen’ 的员工的 manager 的信息。
内连接与外连接
除了查询满足条件的记录以外,外连接还可以查询某一方不满足条件的记录。
- 内连接: 合并具有同一列的两个以上的表的行, 结果集中不包含一个表与另一个表不匹配的行
- 外连接: 两个表在连接过程中除了返回满足连接条件的行以外还返回左(或右)表中不满足条件的行,这种连接称为左(或右)外连接。没有匹配的行时, 结果表中相应的列为空(NULL)。
- 如果是左外连接,则连接条件中左边的表也称为 主表 ,右边的表称为 从表 。 如果是右外连接,则连接条件中右边的表也称为 主表,左边的表称为 从表 。
SQL92:使用(+)创建连接
- 在 SQL92 中采用(+)代表从表所在的位置。即左或右外连接中,(+) 表示哪个是从表。
- Oracle 对 SQL92 支持较好,而 MySQL 则不支持 SQL92 的外连接。
#左外连接 SELECT last_name,department_name FROM employees ,departments WHERE employees.department_id = departments.department_id(+); #右外连接 SELECT last_name,department_name FROM employees ,departments WHERE employees.department_id(+) = departments.department_id;
- 而且在 SQL92 中,只有左外连接和右外连接,没有满(或全)外连接。
演示代码
#7. 多表查询的分类 /* 角度1--针对连接条件:等值连接 vs 非等值连接 角度2:自连接 vs 非自连接 角度3:内连接 vs 外连接 */ # 7.1 等值连接 vs 非等值连接 #上面的多表查询都是等值连接^ #非等值连接的例子: SELECT * FROM job_grades; /*job_grades预览:工资分成了A-F等 +-------------+------------+-------------+ | grade_level | lowest_sal | highest_sal | +-------------+------------+-------------+ | A | 1000 | 2999 | | B | 3000 | 5999 | | C | 6000 | 9999 | | D | 10000 | 14999 | | E | 15000 | 24999 | | F | 25000 | 40000 | +-------------+------------+-------------+ */ #非等值连接的例子: #根据job_grades和具体工资,显示grade_level SELECT e.last_name,e.salary,j.grade_level FROM employees e,job_grades j #where e.`salary` between j.`lowest_sal` and j.`highest_sal`; WHERE e.`salary` >= j.`lowest_sal` AND e.`salary` <= j.`highest_sal`; /* +-------------+----------+-------------+ | last_name | salary | grade_level | +-------------+----------+-------------+ | King | 24000.00 | E | | Kochhar | 17000.00 | E | | De Haan | 17000.00 | E | | Hunold | 9000.00 | C | | Ernst | 6000.00 | C | | Austin | 4800.00 | B | */ #7.2 自连接 vs 非自连接 SELECT * FROM employees; /*部分输出 +-------------+-------------+-------------+----------+--------------------+------------+------------+----------+----------------+------------+---------------+ | employee_id | first_name | last_name | email | phone_number | hire_date | job_id | salary | commission_pct | manager_id | department_id | +-------------+-------------+-------------+----------+--------------------+------------+------------+----------+----------------+------------+---------------+ | 100 | Steven | King | SKING | 515.123.4567 | 1987-06-17 | AD_PRES | 24000.00 | NULL | NULL | 90 | | 101 | Neena | Kochhar | NKOCHHAR | 515.123.4568 | 1989-09-21 | AD_VP | 17000.00 | NULL | 100 | 90 | */ #自连接对应自我引用的情况 #自连接的例子: #练习:查询员工id,员工姓名及其管理者的id和姓名 SELECT emp.employee_id,emp.last_name,mgr.employee_id,mgr.last_name FROM employees emp ,employees mgr #自连接:同一张表的连接,可以理解为同一张表的两个“拷贝表“相连接 WHERE emp.`manager_id` = mgr.`employee_id`; /*部分输出 +-------------+-------------+-------------+-----------+ | employee_id | last_name | employee_id | last_name | +-------------+-------------+-------------+-----------+ | 101 | Kochhar | 100 | King | | 102 | De Haan | 100 | King | | 103 | Hunold | 102 | De Haan | | 104 | Ernst | 103 | Hunold | | 105 | Austin | 103 | Hunold | */ #7.3 内连接 vs 外连接 # 内连接:合并具有同一列的两个以上的表的行, 结果集中不包含一个表与另一个表不匹配的行 SELECT employee_id,department_name FROM employees e,departments d WHERE e.`department_id` = d.department_id; #只有106条记录 # 外连接:合并具有同一列的两个以上的表的行, 结果集中除了包含一个表与另一个表匹配的行之外, # 还查询到了左表 或 右表中不匹配的行。 # 外连接的分类:左外连接、右外连接、满外连接 # 左外连接:两个表在连接过程中除了返回满足连接条件的行以外还返回左表中不满足条件的行,这种连接称为左外连接。 # 右外连接:两个表在连接过程中除了返回满足连接条件的行以外还返回右表中不满足条件的行,这种连接称为右外连接。 #练习:查询所有的员工的last_name,department_name信息 #所有的-->外连接 SELECT employee_id,department_name FROM employees e,departments d WHERE e.`department_id` = d.department_id; # 需要使用左外连接
3 SQL99语法实现多表查询
3.1 基本语法
使用JOIN…ON子句创建连接的语法结构:
SELECT table1.column, table2.column,table3.column FROM table1 JOIN table2 ON table1 和 table2 的连接条件 JOIN table3 ON table2 和 table3 的连接条件
它的嵌套逻辑类似我们使用的 FOR 循环:
for t1 in table1: for t2 in table2: if condition1: for t3 in table3: if condition2: output t1 + t2 + t3
SQL99 采用的这种嵌套结构非常清爽、层次性更强、可读性更强,即使再多的表进行连接也都清晰可见。如果你采用 SQL92,可读性就会大打折扣。
语法说明:
- 可以使用 ON 子句指定额外的连接条件。
- 这个连接条件是与其它条件分开的。
- ON 子句使语句具有更高的易读性。
- 关键字 JOIN、INNER JOIN、CROSS JOIN 的含义是一样的,都表示内连接
3.2 内连接(inner join)的实现
语法:
SELECT 字段列表 FROM A表 INNER JOIN B表 ON 关联条件 WHERE 等其他子句;
题目1:
SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e JOIN departments d ON (e.department_id = d.department_id); /* +-------------+-------------+---------------+---------------+-------------+ | employee_id | last_name | department_id | department_id | location_id | +-------------+-------------+---------------+---------------+-------------+ | 103 | Hunold | 60 | 60 | 1400 | | 104 | Ernst | 60 | 60 | 1400 | | 105 | Austin | 60 | 60 | 1400 | | 106 | Pataballa | 60 | 60 | 1400 | | 107 | Lorentz | 60 | 60 | 1400 | | 120 | Weiss | 50 | 50 | 1500 | | 121 | Fripp | 50 | 50 | 1500 | | 122 | Kaufling | 50 | 50 | 1500 | */
题目2:
SELECT employee_id, city, department_name FROM employees e JOIN departments d ON d.department_id = e.department_id JOIN locations l ON d.location_id = l.location_id; /*部分输出 +-------------+---------------------+------------------+ | employee_id | city | department_name | +-------------+---------------------+------------------+ | 200 | Seattle | Administration | | 201 | Toronto | Marketing | | 202 | Toronto | Marketing | | 114 | Seattle | Purchasing */
3.3 外连接(outer join)的实现
3.3.1 左外连接
语法:
#实现查询结果是A SELECT 字段列表 FROM A表 LEFT JOIN B表 ON 关联条件 WHERE 等其他子句;
举例:
SELECT e.last_name, e.department_id, d.department_name FROM employees e LEFT OUTER JOIN departments d ON (e.department_id = d.department_id) ; /* +-------------+---------------+------------------+ | last_name | department_id | department_name | +-------------+---------------+------------------+ | King | 90 | Executive | | Kochhar | 90 | Executive | | De Haan | 90 | Executive | | Hunold | 60 | IT | | Ernst | 60 | IT | | Austin | 60 | IT | | Pataballa | 60 | IT | | Lorentz | 60 | IT | */
3.3.2 右外连接
语法:
FROM A表 RIGHT JOIN B表 ON 关联条件 WHERE 等其他子句;
举例:
SELECT e.last_name, e.department_id, d.department_name FROM employees e RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id) ; /* +-------------+---------------+----------------------+ | last_name | department_id | department_name | +-------------+---------------+----------------------+ | Whalen | 10 | Administration | | Hartstein | 20 | Marketing | | Fay | 20 | Marketing | | Raphaely | 30 | Purchasing | | Khoo | 30 | Purchasing | */
需要注意的是,LEFT JOIN 和 RIGHT JOIN 只存在于 SQL99 及以后的标准中,在 SQL92 中不存在,只能用 (+) 表示。
3.3.3 满外连接
- 满外连接的结果 = 左右表匹配的数据 + 左表没有匹配到的数据 + 右表没有匹配到的数据。
- SQL99是支持满外连接的。使用FULL JOIN 或 FULL OUTER JOIN来实现。
- 需要注意的是,MySQL不支持FULL JOIN,但是可以用 LEFT JOIN UNION RIGHT join代替。
演示代码
#SQL92语法实现内连接:见上,略 #SQL92语法实现外连接:使用 + ----------MySQL不支持SQL92语法中外连接的写法! #Mysql不支持,Oracle支持: SELECT employee_id,department_name FROM employees e,departments d WHERE e.`department_id` = d.department_id(+);#编译不过 #SQL99语法中使用 JOIN ...ON 的方式实现多表的查询。这种方式也能解决外连接的问题。MySQL是支持此种方式的。 #SQL99语法如何实现多表的查询。 #SQL99语法实现内连接: SELECT last_name,department_name FROM employees e INNER JOIN departments d ON e.`department_id` = d.`department_id`; #INNER可省略 /*部分输出 +-------------+------------------+ | last_name | department_name | +-------------+------------------+ | Whalen | Administration | | Hartstein | Marketing | | Fay | Marketing | */ #三张表的内连接 SELECT last_name,department_name,city FROM employees e JOIN departments d ON e.`department_id` = d.`department_id` JOIN locations l ON d.`location_id` = l.`location_id`; /*部分输出 +-------------+------------------+---------------------+ | last_name | department_name | city | +-------------+------------------+---------------------+ | Whalen | Administration | Seattle | | Hartstein | Marketing | Toronto | | Fay | Marketing | Toronto | */ #SQL99语法实现外连接: #练习:查询所有的员工的last_name,department_name信息 #左、右外连接OUTER可省略 # 左外连接: SELECT last_name,department_name FROM employees e LEFT JOIN departments d ON e.`department_id` = d.`department_id`;#107条记录 #右外连接: SELECT last_name,department_name FROM employees e RIGHT OUTER JOIN departments d ON e.`department_id` = d.`department_id`;#122条记录 #满外连接:mysql不支持FULL OUTER JOIN,Oracle支持: SELECT last_name,department_name FROM employees e FULL OUTER JOIN departments d ON e.`department_id` = d.`department_id`;
4 union的使用
合并查询结果 利用UNION关键字,可以给出多条SELECT语句,并将它们的结果组合成单个结果集。合并时,两个表对应的列数和数据类型必须相同,并且相互对应。各个SELECT语句之间使用UNION或UNION ALL关键字分隔。
语法格式:
SELECT column,... FROM table1 UNION [ALL] SELECT column,... FROM table2
4.1 union操作符
UNION 操作符返回两个查询的结果集的并集,去除重复记录。
4.2 union all操作符
UNION ALL操作符返回两个查询的结果集的并集。对于两个结果集的重复部分,不去重。
注意:执行UNION ALL语句时所需要的资源比UNION语句少。如果明确知道合并数据后的结果数据不存在重复数据,或者不需要去除重复的数据,则尽量使用UNION ALL语句,以提高数据查询的效率
举例:查询部门编号>90或邮箱包含a的员工信息
#方式1 SELECT * FROM employees WHERE email LIKE '%a%' OR department_id>90; #方式2 SELECT * FROM employees WHERE email LIKE '%a%' UNION SELECT * FROM employees WHERE department_id>90;
举例:查询中国用户中男性的信息以及美国用户中年男性的用户信息
SELECT id,cname FROM t_chinamale WHERE csex='男' UNION ALL SELECT id,tname FROM t_usmale WHERE tGender='male';
代码演示
#8. UNION 和 UNION ALL的使用 # UNION:会执行去重操作 # UNION ALL:不会执行去重操作,效率优于前者,开发中优先使用 #结论:如果明确知道合并数据后的结果数据不存在重复数据,或者不需要去除重复的数据, #则尽量使用UNION ALL语句,以提高数据查询的效率。
5 7种SQL JOINS的实现
5.1 代码实现
#中图:内连接 A∩B SELECT employee_id,last_name,department_name FROM employees e JOIN departments d ON e.`department_id` = d.`department_id`; #左上图:左外连接 SELECT employee_id,last_name,department_name FROM employees e LEFT JOIN departments d ON e.`department_id` = d.`department_id`; #右上图:右外连接 SELECT employee_id,last_name,department_name FROM employees e RIGHT JOIN departments d ON e.`department_id` = d.`department_id`; #左中图:A - A∩B SELECT employee_id,last_name,department_name FROM employees e LEFT JOIN departments d ON e.`department_id` = d.`department_id` WHERE d.`department_id` IS NULL #右中图:B-A∩B SELECT employee_id,last_name,department_name FROM employees e RIGHT JOIN departments d ON e.`department_id` = d.`department_id` WHERE e.`department_id` IS NULL #左下图:满外连接 # 左中图 + 右上图 A∪B SELECT employee_id,last_name,department_name FROM employees e LEFT JOIN departments d ON e.`department_id` = d.`department_id` WHERE d.`department_id` IS NULL UNION ALL #没有去重操作,效率高 SELECT employee_id,last_name,department_name FROM employees e RIGHT JOIN departments d ON e.`department_id` = d.`department_id`; #右下图 #左中图 + 右中图 A ∪B- A∩B 或者 (A - A∩B) ∪ (B - A∩B) SELECT employee_id,last_name,department_name FROM employees e LEFT JOIN departments d ON e.`department_id` = d.`department_id` WHERE d.`department_id` IS NULL UNION ALL SELECT employee_id,last_name,department_name FROM employees e RIGHT JOIN departments d ON e.`department_id` = d.`department_id` WHERE e.`department_id` IS NULL
5.2 语法格式小结
左中图
#实现A - A∩B select 字段列表 from A表 left join B表 on 关联条件 where 从表关联字段 is null and 等其他子句;
右中图
#实现B - A∩B select 字段列表 from A表 right join B表 on 关联条件 where 从表关联字段 is null and 等其他子句;
左下图
#实现查询结果是A∪B #用左外的A,union 右外的B select 字段列表 from A表 left join B表 on 关联条件 where 等其他子句 union select 字段列表 from A表 right join B表 on 关联条件 where 等其他子句;
右下图
#实现A∪B - A∩B 或 (A - A∩B) ∪ (B - A∩B) #使用左外的 (A - A∩B) union 右外的(B - A∩B) select 字段列表 from A表 left join B表 on 关联条件 where 从表关联字段 is null and 等其他子句 union select 字段列表 from A表 right join B表 on 关联条件 where 从表关联字段 is null and 等其他子句
代码演示
#9. 7种JOIN的实现: # 中图:内连接 SELECT employee_id,department_name FROM employees e JOIN departments d ON e.`department_id` = d.`department_id`;#106条记录 # 左上图:左外连接 SELECT employee_id,department_name FROM employees e LEFT JOIN departments d ON e.`department_id` = d.`department_id`;#107条记录 # 右上图:右外连接 SELECT employee_id,department_name FROM employees e RIGHT JOIN departments d ON e.`department_id` = d.`department_id`;#122条记录 # 左中图(在左上图中抹去中间部分): SELECT employee_id,department_name FROM employees e LEFT JOIN departments d ON e.`department_id` = d.`department_id` WHERE d.`department_id` IS NULL;#1条记录 # 右中图(在右上图中抹去中间部分): SELECT employee_id,department_name FROM employees e RIGHT JOIN departments d ON e.`department_id` = d.`department_id` WHERE e.`department_id` IS NULL;#16条记录 # 左下图:满外连接 # 方式1:左上图 UNION ALL 右中图 SELECT employee_id,department_name FROM employees e LEFT JOIN departments d ON e.`department_id` = d.`department_id` UNION ALL SELECT employee_id,department_name FROM employees e RIGHT JOIN departments d ON e.`department_id` = d.`department_id` WHERE e.`department_id` IS NULL;#123条记录 # 方式2:左中图 UNION ALL 右上图 SELECT employee_id,department_name FROM employees e LEFT JOIN departments d ON e.`department_id` = d.`department_id` WHERE d.`department_id` IS NULL UNION ALL SELECT employee_id,department_name FROM employees e RIGHT JOIN departments d ON e.`department_id` = d.`department_id`;#123条记录 # 右下图:左中图 UNION ALL 右中图 SELECT employee_id,department_name FROM employees e LEFT JOIN departments d ON e.`department_id` = d.`department_id` WHERE d.`department_id` IS NULL UNION ALL SELECT employee_id,department_name FROM employees e RIGHT JOIN departments d ON e.`department_id` = d.`department_id` WHERE e.`department_id` IS NULL; #17条记录
6 SQL99语法新特性
6.1 自然连接
SQL99 在 SQL92 的基础上提供了一些特殊语法,比如 NATURAL JOIN 用来表示自然连接。我们可以把自然连接理解为 SQL92 中的等值连接。它会帮你自动查询两张连接表中 所有相同的字段 ,然后进行 等值连接 。
在SQL92标准中:
SELECT employee_id,last_name,department_name FROM employees e JOIN departments d ON e.`department_id` = d.`department_id` AND e.`manager_id` = d.`manager_id`;
在 SQL99 中你可以写成:
SELECT employee_id,last_name,department_name FROM employees e NATURAL JOIN departments d;
6.2 using连接
当我们进行连接的时候,SQL99还支持使用 USING 指定数据表里的 同名字段 进行等值连接。但是只能配合JOIN一起使用。比如:
SELECT employee_id,last_name,department_name FROM employees e JOIN departments d USING (department_id);
你能看出与自然连接 NATURAL JOIN 不同的是,USING 指定了具体的相同的字段名称,你需要在 USING的括号 () 中填入要指定的同名字段。同时使用 JOIN…USING 可以简化 JOIN ON 的等值连接。它与下面的 SQL 查询结果是相同的:
SELECT employee_id,last_name,department_name FROM employees e ,departments d WHERE e.department_id = d.department_id;
表连接的约束条件可以有三种方式:WHERE, ON, USING
- WHERE:适用于所有关联查询
- ON :只能和JOIN一起使用,只能写关联条件。虽然关联条件可以并到WHERE中和其他条件一起写,但分开写可读性更好。
- USING:只能和JOIN一起使用,而且要求两个关联字段在关联表中名称一致,而且只能表示关联字段值相等
#关联条件 #把关联条件写在where后面 SELECT last_name,department_name FROM employees,departments WHERE employees.department_id = departments.department_id; #把关联条件写在on后面,只能和JOIN一起使用 SELECT last_name,department_name FROM employees INNER JOIN departments ON employees.department_id = departments.department_id; SELECT last_name,department_name FROM employees CROSS JOIN departments ON employees.department_id = departments.department_id; SELECT last_name,department_name FROM employees JOIN departments ON employees.department_id = departments.department_id; #把关联字段写在using()中,只能和JOIN一起使用 #而且两个表中的关联字段必须名称相同,而且只能表示= #查询员工姓名与基本工资 SELECT last_name,job_title FROM employees INNER JOIN jobs USING(job_id); #n张表关联,需要n-1个关联条件 #查询员工姓名,基本工资,部门名称 SELECT last_name,job_title,department_name FROM employees,departments,jobs WHERE employees.department_id = departments.department_id AND employees.job_id = jobs.job_id; SELECT last_name,job_title,department_name FROM employees INNER JOIN departments INNER JOIN jobs ON employees.department_id = departments.department_id AND employees.job_id = jobs.job_id;
注意:
我们要 控制连接表的数量 。多表连接就相当于嵌套 for 循环一样,非常消耗资源,会让 SQL查询性能下降得很严重,因此不要连接不必要的表。在许多 DBMS 中,也都会有最大连接表的限制。
来源:阿里巴巴《Java开发手册》
【强制】超过三个表禁止 join。需要 join 的字段,数据类型保持绝对一致;多表关联查询时, 保证被关联的字段需要有索引。
说明:即使双表 join 也要注意表索引、SQL 性能。
代码演示
#10. SQL99语法的新特性1:自然连接 # employees表和departments 表有两个字段相同 SELECT employee_id,last_name,department_name FROM employees e JOIN departments d ON e.`department_id` = d.`department_id` AND e.`manager_id` = d.`manager_id`;#32条记录 #或 # NATURAL JOIN : 它会帮你自动查询两张连接表中`所有相同的字段`,然后进行`等值连接`。 SELECT employee_id,last_name,department_name FROM employees e NATURAL JOIN departments d;#32条记录 /*以上两种方式效果一样: +-------------+------------+-----------------+ | employee_id | last_name | department_name | +-------------+------------+-----------------+ | 202 | Fay | Marketing | | 115 | Khoo | Purchasing | | 116 | Baida | Purchasing | | 117 | Tobias | Purchasing | | 118 | Himuro | Purchasing | */ #11. SQL99语法的新特性2:USING SELECT employee_id,last_name,department_name FROM employees e JOIN departments d ON e.department_id = d.department_id; SELECT employee_id,last_name,department_name FROM employees e JOIN departments d USING (department_id); #拓展写法: SELECT last_name,job_title,department_name FROM employees INNER JOIN departments INNER JOIN jobs ON employees.department_id = departments.department_id AND employees.job_id = jobs.job_id;
附录:常用的SQL标准有哪些
在正式开始讲连接表的种类时,我们首先需要知道 SQL 存在不同版本的标准规范,因为不同规范下的表连接操作是有区别的。
SQL 有两个主要的标准,分别是 SQL92 和 SQL99 。92 和 99 代表了标准提出的时间,SQL92 就是 92 年提出的标准规范。当然除了 SQL92 和 SQL99 以外,还存在 SQL-86、SQL-89、SQL:2003、SQL:2008、SQL:2011 和 SQL:2016 等其他的标准。
这么多标准,到底该学习哪个呢?实际上最重要的 SQL 标准就是 SQL92 和 SQL99。一般来说 SQL92 的形式更简单,但是写的 SQL 语句会比较长,可读性较差。而 SQL99 相比于 SQL92 来说,语法更加复杂,但可读性更强。我们从这两个标准发布的页数也能看出,SQL92 的标准有 500 页,而 SQL99 标准超过了1000 页。实际上从 SQL99 之后,很少有人能掌握所有内容,因为确实太多了。就好比我们使用Windows、Linux 和 Office 的时候,很少有人能掌握全部内容一样。只需要掌握一些核心的功能,满足日常工作的需求即可。
SQL92 和 SQL99 是经典的 SQL 标准,也分别叫做 SQL-2 和 SQL-3 标准。也正是在这两个标准发布之后,SQL 影响力越来越大,甚至超越了数据库领域。现如今 SQL 已经不仅仅是数据库领域的主流语言,还是信息领域中信息处理的主流语言。在图形检索、图像检索以及语音检索中都能看到 SQL 语言的使用。
课后练习
# 第06章_多表查询的课后练习 # 1.显示所有员工的姓名,部门号和部门名称。 SELECT e.last_name,e.department_id,d.department_name FROM employees e LEFT OUTER JOIN departments d ON e.`department_id` = d.`department_id`; /*部分输出 +-------------+---------------+------------------+ | last_name | department_id | department_name | +-------------+---------------+------------------+ | King | 90 | Executive | | Kochhar | 90 | Executive | | De Haan | 90 | Executive | | Hunold | 60 | IT | | Ernst | 60 | IT | | Austin | 60 | IT | */ # 2.查询90号部门员工的job_id和90号部门的location_id SELECT e.job_id,d.location_id FROM employees e JOIN departments d ON e.`department_id` = d.`department_id` WHERE d.`department_id` = 90; /*输出、 +---------+-------------+ | job_id | location_id | +---------+-------------+ | AD_PRES | 1700 | | AD_VP | 1700 | | AD_VP | 1700 | +---------+-------------+ */ DESC departments; # 3.选择所有有奖金的员工的 last_name , department_name , location_id , city #所有有奖金的员工-->左外连接 SELECT e.last_name ,e.`commission_pct`, d.department_name , d.location_id , l.city FROM employees e LEFT JOIN departments d ON e.`department_id` = d.`department_id` LEFT JOIN locations l ON d.`location_id` = l.`location_id` WHERE e.`commission_pct` IS NOT NULL; #也应该是35条记录 /*部分输出 +------------+----------------+-----------------+-------------+--------+ | last_name | commission_pct | department_name | location_id | city | +------------+----------------+-----------------+-------------+--------+ | Russell | 0.40 | Sales | 2500 | Oxford | | Partners | 0.30 | Sales | 2500 | Oxford | | Errazuriz | 0.30 | Sales | 2500 | Oxford | | Cambrault | 0.30 | Sales | 2500 | Oxford | | Zlotkey | 0.20 | Sales | 2500 | Oxford | | Tucker | 0.30 | Sales | 2500 | Oxford | | Bernstein | 0.25 | Sales | 2500 | Oxford | | Hall | 0.25 | Sales | 2500 | Oxford | | Olsen | 0.20 | Sales | 2500 | Oxford | */ SELECT * FROM employees WHERE commission_pct IS NOT NULL; #35条记录 #练习 SELECT employee_id FROM departments d LEFT JOIN employees e ON d.`department_id`=e.`department_id` WHERE d.`department_name` ='Sales' OR d.`department_name` ='Sales'; # 4.选择city在Toronto工作的员工的 last_name , job_id , department_id , department_name SELECT e.last_name , e.job_id , e.department_id , d.department_name FROM employees e JOIN departments d ON e.`department_id` = d.`department_id` JOIN locations l ON d.`location_id` = l.`location_id` WHERE l.`city` = 'Toronto'; /* +-----------+--------+---------------+-----------------+ | last_name | job_id | department_id | department_name | +-----------+--------+---------------+-----------------+ | Hartstein | MK_MAN | 20 | Marketing | | Fay | MK_REP | 20 | Marketing | +-----------+--------+---------------+-----------------+ */ #sql92语法: SELECT e.last_name , e.job_id , e.department_id , d.department_name FROM employees e,departments d ,locations l WHERE e.`department_id` = d.`department_id` AND d.`location_id` = l.`location_id` AND l.`city` = 'Toronto'; # 5.查询员工所在的部门名称、部门地址、姓名、工作、工资,其中员工所在部门的部门名称为’Executive’ SELECT d.department_name,l.street_address,e.last_name,e.job_id,e.salary FROM departments d LEFT JOIN employees e ON e.`department_id` = d.`department_id` LEFT JOIN locations l ON d.`location_id` = l.`location_id` WHERE d.`department_name` = 'Executive'; /* +-----------------+-----------------+-----------+---------+----------+ | department_name | street_address | last_name | job_id | salary | +-----------------+-----------------+-----------+---------+----------+ | Executive | 2004 Charade Rd | King | AD_PRES | 24000.00 | | Executive | 2004 Charade Rd | Kochhar | AD_VP | 17000.00 | | Executive | 2004 Charade Rd | De Haan | AD_VP | 17000.00 | +-----------------+-----------------+-----------+---------+----------+ */ DESC departments; DESC locations; # 6.选择指定员工的姓名,员工号,以及他的管理者的姓名和员工号,结果类似于下面的格式 employees Emp# manager Mgr# kochhar 101 king 100 SELECT emp.last_name "employees",emp.employee_id "Emp#",mgr.last_name "manager", mgr.employee_id "Mgr#" FROM employees emp LEFT JOIN employees mgr ON emp.manager_id = mgr.employee_id; /*部分输出(107条记录) +-------------+------+-----------+------+ | employees | Emp# | manager | Mgr# | +-------------+------+-----------+------+ | King | 100 | NULL | NULL | | Kochhar | 101 | King | 100 | | De Haan | 102 | King | 100 | | Hunold | 103 | De Haan | 102 | | Ernst | 104 | Hunold | 103 | | Austin | 105 | Hunold | 103 | | Pataballa | 106 | Hunold | 103 | | Lorentz | 107 | Hunold | 103 | */ # 7.查询哪些部门没有员工 #方式1: SELECT d.department_id FROM departments d LEFT JOIN employees e ON d.`department_id` = e.`department_id` WHERE e.`department_id` IS NULL; #方式2: SELECT department_id FROM departments d WHERE NOT EXISTS ( SELECT * FROM employees e WHERE e.`department_id` = d.`department_id` ); /* +---------------+ | department_id | +---------------+ | 120 | | 130 | | 140 | | 150 | | 160 | | 170 | | 180 | | 190 | | 200 | | 210 | | 220 | | 230 | | 240 | | 250 | | 260 | | 270 | +---------------+ 16 rows in set (0.00 sec) */ #本题也可以使用子查询:暂时不讲 # 8. 查询哪个城市没有部门 SELECT l.location_id,l.city FROM locations l LEFT JOIN departments d ON l.`location_id` = d.`location_id` WHERE d.`location_id` IS NULL; /* +-------------+-----------------+ | location_id | city | +-------------+-----------------+ | 1000 | Roma | | 1100 | Venice | | 1200 | Tokyo | | 1300 | Hiroshima | | 1600 | South Brunswick | | 1900 | Whitehorse | | 2000 | Beijing | | 2100 | Bombay | | 2200 | Sydney | | 2300 | Singapore | | 2600 | Stretford | | 2800 | Sao Paulo | | 2900 | Geneva | | 3000 | Bern | | 3100 | Utrecht | | 3200 | Mexico City | +-------------+-----------------+ */ SELECT department_id FROM departments WHERE department_id IN (1000,1100,1200,1300,1600); # 9. 查询部门名为 Sales 或 IT 的员工信息 SELECT e.employee_id,e.last_name,e.department_id FROM employees e JOIN departments d ON e.`department_id` = d.`department_id` WHERE d.`department_name` IN ('Sales','IT'); /*部分输出(39条记录) +-------------+------------+---------------+ | employee_id | last_name | department_id | +-------------+------------+---------------+ | 103 | Hunold | 60 | | 104 | Ernst | 60 | | 105 | Austin | 60 | */