数据库SQL的多表查询

数据库 SQL 的多表查询:eg: table1: employees, table2: departments,table3: salary_grades;

	一:内连接:
1):等值连接:
把表employees中的department_id 与表departmes中的department_id相匹配的找出来
select e.last_name, d.department_id
from employees e,departments d
where e.department_id = d.department_id --等值内连接的缺点是:筛选条件中没有匹配的则无法选出; 2):非等值连接:
把表employees中的salary按照表salary_grades中的等级进行分配等级:
select last_name ,salary,grade_level
from employees,job_grades
where salary between lowest_sal and highest_sal 二:外连接:
--相对于内连接中的等值连接,等值连接的缺点显而易见,要想把不匹配的内容显现出来,则要使用外连接; 1):左连接: 右边去匹配左边的内容,把匹配不到的左边的原样输出,要在等式右边加上'(+)';
select e.last_name, d.department_id
from employees e,departments d
where e.department_id = d.department_id(+) 2):右连接: 左边去匹配右边的内容,把匹配不到的右边的原样输出,要在等式左边加上'(+)';
select e.last_name, d.department_id
from employees e,departments d
where e.department_id(+) = d.department_id --外连接也是有缺陷的,它的缺陷是:左右连接不能同时使用,要想同时输出两边都不匹配的,需要用到SQL99: 三: SQL99:
--SQL99又是另一套体系; 1): --针对上述外连接的缺陷,SQL99可以使用natural join 来解决:
select last_name, department_id
from employees e natural join departments d --他的缺陷是自动匹配两个表中列名称完全一样并且数据类型完全相同的{所有列中}的(不只是目标列)情况; 2): --针对上述1)的缺陷,可以考虑使用以下的:
select last_name, d.department_id
from employees e join departments d
on e.department_id = d.department_id --和where的意思一样 3):
select last_name, department_id
from employees join departments
using(department_id) --这种方式需要两个表中的列名陈和数据类型完全一样 4): 左连接:
select last_name, d.department_id
from employees e left outer join departments d
on e.department_id = d.department_id 5): 右连接:
select last_name, d.department_id
from employees e right outer join departments d
on e.department_id = d.department_id 6): 全连接:
select last_name, d.department_id
from employees e full outer join departments d
on e.department_id = d.department_id 四: 自连接:
--去实现查询表employees中last_name = 'chen' 的员工的老板的工资和email:
select emp.last_name,emp.manager_id,managers.salary,managers.email
from employees emp,employees managers
where emp.manager_id = managers.employee_id and lower(emp.last_name) = 'chen'

  

上一篇:Android 四大组件之Activity(续2)


下一篇:HackerRank "Morgan and a String"