UNION的使用
给出将多条查询语句组合成单个结果集,两个表对应的列数和数据类型必须相同
UNION操作符:
返回两个查询结果集的并集,并去除重复记录
UNION ALL操作符
返回两个查询的结果集的并集。不去掉两个结果集的重复部分,重复部分会显示两次
若不需要去除数据或不存在重复数据,尽量使用UNION ALL,
UNION ALL使用资源比UNION少,查询效率高
满外连接操作:LEFT JOIN UNION RIGHT JOIN
SELECT last_name,department_name
FROM employees e LEFT JOIN departments d
ON e.'department_id' = d.'department_id'
UNION
SELECT last_name,department_name
FROM employees e RIGHT JOIN departments d
ON e.'department_id' = d.'department_id';
查询121条记录,包括无部门的员工和部门无员工的记录
7种QL JOINS的实现
包括想实现满外连接,可以有多种组合实现
通过UNION ALL也可以实现无重复的满外连接
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 employees_id,last_name,department_name
FROM employees e RIGHT JOIN departments d
ON e.'department_id' = d.'department_id';
自然连接
SQL99特殊语法NATURAL JOIN
可以看到两个表中有多个关联字段
那么,两个表连接时,就可以使用这两个关联字段
SELECT last_name,department_name
FROM employees e, departments d
WHERE e.'department_id' = d.'department_id'
AND e.'manager_id' = d.'manager_id';
自然连接:
自动查询两张表中相同的字段,并进行等值连接
SELECT last_name, department_name
FROM employees NATURAL JOIN departments;
和上面那个结果集一样
USING连接
使用关联字段连接两个表
SELECT last_name,department_name
FROM employees e JOIN departments d
ON e.'department_id' = d.'department_id';
当关联字段在两个表中,名字一样时,可以使用USING关键字
SELECT last_name, department_name
FROM employees JOIN departments
USING(department_id);
将ON用USING代替,将两个字段进行等值连接
不能用与自连接