[Oracle 学习笔记] 05 连接查询
内连接查询
内连接查询组合两国或多个表(视图)中的数据,其查询结果含有多个原表中的相关数据。内连接查询返回满足连接条件的记录航,删除不满足连接条件和匹配列中带有NULL值的记录行。
SQL> SELECT teacher_id, name, department_name FROM teachers, departments WHERE teachers.department_id = departments.department_id;
外连接查询
左外连接
左外连接查询添加回内连接查询从第一个表中删除的所有行。NULL值被防区其他表的列中。
SQL> SELECT teacher_id, name, department_name FROM teachers t, departments d WHERE t.departments_id= d.department_id(+);
SQL> SELECT teacher_id, name, department_name FROM teachers t LEFT OUTER JOIN departments d ON t.department_id=d.department_id;
右外连接
右外连接查询添加会内连接查询从第二个表中删除的所有行。
SQL> SELECT teacher_id, name, department_name FROM teachers t, departments d WHERE t.department_id(+) = d.department_id;
SQL>SELECT teacher_id, name, department_name FROM teachers t RIGHT OUTER JOIN departments d ON t.department_id = d.department_id;
全外连接
添加回了内连接查询从两个表中删除的所有行。
SQL> SELECT teacher_id, name, department_name FROM teachers t, deparments d WHERE t.department_id = d.department_id(+)
UNION
SELECT teacher_id, name, department_name FROM teachers t, departments d WHERE t.department_id(+) = d.department_id;
SQL> SELECT teacher_id, name, department_name FROM teachers t FULL OUTER JOIN departments d ON t.department_id = d.department_id;
交叉连接
交叉连接(笛卡尔乘积)查询不常用,交叉连接是其他连接的基础,所以具有很多记录(m*n),所以应该只将他用户小型表(记录行少),避免对大型表(记录行多)进行交叉连接。
SQL> SELECT teacher_id, name, department_name FROM teachers, departments;
自连接
某个表与自身进行的连接查询,如果同一时间需要同一个表中两个不同行中的信息,则需要将表与自身进行连接。
SQL> SELECT s1.student_id, s1.name AS "学生名", s1.monitor_id, s2.name AS "班长名" FROM students s1, students s2 WHERE s1.monitor_id = s2.student_id(+)