SlideShare a Scribd company logo
Oracle OCP 考试系列培训
                之
         1Z0-007 Lesson5
                   www.OracleOnLinux.cn




5-1   Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
5
                     Displaying Data
                  from Multiple Tables




5-2   Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Objectives


      After completing this lesson, you should be able to do
      the following:
       • Write SELECT statements to access data from
           more than one table using equijoins and non-
           equijoins
       • Join a table to itself by using a self-join
       • View data that generally does not meet a join
           condition by using outer joins
       • Generate a Cartesian product of all rows from two
           or more tables




5-3          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Obtaining Data from Multiple Tables


      EMPLOYEES                               DEPARTMENTS


      …




                        …



5-4         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Oracle 的多表查询


      使用连接从多个表中查询数据;

      SELECT last_name,department_name
      SELECT last_name,department_name
             last_name,department_name
             last_name,department_name
      FROM employees,departments;
      FROM employees,departments;



      产生笛卡尔乘积.




5-5        Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
连接的类型


      Oracle 以前的连接 (8i                         SQL: 1999
       and prior 90SQL):
                 90SQL):                       适应性连接:
      等值连接 -- Equijoin                        交叉连接 -- Cross joins
      非等值连接 -- Non-equijoin                   自然连接 -- Natural joins
      外连接 -- Outer join                       使用Using子句的连接
      自连接 -- Self join                        完全外连接或者左、右外连接




5-6         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
使用 Oracle 的语法连接多个表


      使用连接从多个表中查询数据.
      SELECT
      SELECT     table1.column, table2.column
                 table1.column, table2.column
      FROM
      FROM       table1, table2
                 table1, table2
      WHERE
      WHERE      table1.column1 = table2.column2;
                 table1.column1 = table2.column2;

      •   在 WHERE 子句中写入连接条件.
      •   当多个表中有重名列时,在列的名字前加上表名作为
          前缀.




5-7        Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
什么是等值连接?
                                   ?
      EMPLOYEES                            DEPARTMENTS




        …                                    …


                        Foreign key         Primary key

5-8         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
使用等值连接查询数据


      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;




      …



5-9         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
使用 AND 操作符增加查询条件


       EMPLOYEES                              DEPARTMENTS




   …                                       …




5-10        Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
使用 AND 操作符增加查询条件


       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
       AND    employees.salary>10000 ;




5-11          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
使用表的别名

       •   使用表的别名简化了查询.
       •   提供虚拟数据源,自连接中更能体现.


       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 e.employee_id, e.last_name, e.department_id,
              d.department_id, departments.location_id
                               departments.location_id
       FROM   employees e , departments d
       WHERE e.department_id = d.department_id;


5-12         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
对多表作等值连接查询
EMPLOYEES                     DEPARTMENTS                        LOCATIONS




…

       为了连接n个表, 至少需要n-1个连接条件.例如,为了连接三
       个表,至少需要两个连接条件.


5-13      Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
对多表作等值连接查询
EMPLOYEES                       DEPARTMENTS                         LOCATIONS                       JOBS
                                                                                                    JOBS
 col job_title for a30
 col last_name for a20
 col department_name for a20
 set linesize 120
 SELECT e.last_name,d.department_name,j.job_title,l.city
 FROM employees e,departments d,jobs j,locations l
 WHERE e.department_id=d.department_id
 AND e.job_id=j.job_id
 AND d.location_id=l.location_id;
  LAST_NAME               DEPARTMENT_NAME                              JOB_TITLE                              CITY
  --------------- ------------------------------ ----------------------------------- ------------------------------
  King               Executive                        President                                      Seattle
  De Haan             Executive                       Administration Vice President                   Seattle
  Kochhar             Executive                       Administration Vice President                   Seattle
  ......


5-14                Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
非等值连接
       EMPLOYEES                         JOB_GRADES




                        在 EMPLOYEES 表中所有薪水
                        位于JOB_GRADES
                           JOB_GRADES
                           JOB_GRADES表最低薪水
       …                和最高薪水之间雇员的薪水信
                        息.
                         .
        除等值连接之外的所有连接都认为是非等值连接。


5-15      Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
使用非等值连接查询数据


       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;




       …


5-16         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
外连接


       DEPARTMENTS                         EMPLOYEES




                                            …
                                             没有雇员属于190部门.


5-17       Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
外连接的语法

       •   为了看到那些不匹配的数据,必须使用外连接.
       •   外连接的操作符为 (+).
                    (+).
       •   不能把连接操作符(+)同时运用在两端(99SQL支持).
       •   等值连接"丢失"记录,外连接则显示所有记录.
       SELECT table1.column, table2.column
       SELECT table1.column, table2.column
       FROM
       FROM   table1, table2
              table1, table2
       WHERE table1.column(+) = table2.column;
       WHERE table1.column(+) = table2.column;
              table1.column(+)
               table1.column(+)

       SELECT
       SELECT   table1.column, table2.column
                table1.column, table2.column
       FROM
       FROM     table1, table2
                table1, table2
       WHERE
       WHERE    table1.column = table2.column(+);
                table1.column = table2.column(+) ;
                                             (+);
                                table2.column(+)
                                 table2.column(+)
                                              (+);




5-18        Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
使用外连接


       SELECT e.last_name, e.department_id, d.department_name
       FROM   employees e, departments d
       WHERE   e.department_id(+) = d.department_id ;




       …




5-19           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
自连接


       EMPLOYEES (WORKER)                           EMPLOYEES (MANAGER)




       …                                          …




               WORKER表中的MANAGER_ID 等于 MANAGER 表中的
               WORKER   MANAGER_ID
                          EMPLOYEE_ID.

5-20        Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
对一张表作自连接查询

       SELECT worker.last_name || ' works for '
              || manager.last_name
       FROM   employees worker, employees manager
       WHERE worker.manager_id = manager.employee_id ;




   …
                      员工的管理者编号就是管理者作为员工的员工编号


5-21         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
使用 SQL: 1999 语法执行表的连接


       使用连接从多个表中查询数据.

       SELECT
       SELECT table1.column, table2.column
                table1.column, table2.column
       FROM
       FROM     table1
                table1
       [CROSS JOIN table2] |
       [CROSS JOIN table2] |
       [NATURAL JOIN table2] |
       [NATURAL JOIN table2] |
       [JOIN table2 USING (column_name)] |
       [JOIN table2 USING (column_name)] |
       [JOIN table2
       [JOIN table2
         ON(table1.column_name = table2.column_name)] |
         ON(table1.column_name = table2.column_name)] |
       [LEFT|RIGHT|FULL OUTER JOIN table2
       [LEFT|RIGHT|FULL OUTER JOIN table2
         ON (table1.column_name = table2.column_name)];
         ON (table1.column_name = table2.column_name)];




5-22        Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
建立交叉连接


       •   CROSS JOIN 子句产生两个表的交叉连接.
       •   产生的结果等于两个表执行笛卡尔乘积.



       SELECT last_name, department_name
       FROM   employees
       CROSS JOIN departments ;




   …


5-23          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
建立自然连接


       •   NATURAL JOIN 子句基于两个表中列名完全相同的多
           个列产生连接.
       •   从两个表中选出连接列的值相等的所有行.
       •   如果两个列的名称相同,但是具有不同的数据类型,则
           查询会返回一个错误.
           –    字段名同,含义不同;(不想连接却连上了)
           –    字段名不同,含义同;(想连却连不上)
           –    字段名同,含义同;(不可以显示指定不连)
           –    不能做非等值连接;




5-24           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
用自然连接查询数据


       SELECT department_id, department_name,
              location_id, city
       FROM   departments
       NATURAL JOIN locations ;




5-25          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
使用 USING 子句建立连接


       •   如果某些列有相同的名称但数据类型不匹配,自然连接
           将出错,可以在自然连接的 NATURAL JOIN 子句上
           使用 USING 子句来设置用于等值连接的列.
       •   不要在引用列上使用表名或者别名作为前缀.
       •   NATURAL JOIN 与 USING
                          USING子句是相互独立的.
           – 能解决同名不同意的问题;
           – 解决不了同意不同名的问题;




5-26        Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
使用 USING 子句查询数据


       SELECT e.employee_id, e.last_name, d.location_id
       FROM   employees e JOIN departments d
       USING (department_id) ;




       …




5-27          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
使用ON
                          ON
                          ON子句建立连接


       •   自然连接的条件是基于表中所有同名列的等值连接.
       •   为了设置任意的连接条件或者指定连接的列,需要使
           用ON
            ON子句.
            ON
       •   连接条件与其它的查询条件分开书写.
       •   使用ON 子句使查询语句更容易理解.
              ON




5-28        Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
使用 ON 子句查询数据


       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);




       …




5-29          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
使用ON
                   ON子句建立Three-Way 连接
                   ON    Three-Way

       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;




       …



5-30            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
INNER 连接与OUTER 连接的对比
                      OUTER


       •   在SQL: 1999中, 两个表的连接只返回匹配行的被叫做
           内连接.
       •   两个表的连接结果既包括了内连接,又包括了不匹配
           左(右)边表的结果集,也就是左(右)外连接.
       •   两个表的连接结果既包含了内连接的结果,也包含了
           左右外连接的结果,被叫做完全连接.




5-31        Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
左外连接

       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) ;




       …




5-32          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
右外连接

       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) ;




       …




5-33          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
完全外连接

       SELECT e.last_name, e.department_id, d.department_name
       FROM   employees e
       FULL OUTER JOIN departments d
       ON   (e.department_id = d.department_id) ;




       …




        注意完全外连接的执行顺序?

5-34          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
增加其他的查询条件

       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)
       AND    e.manager_id = 149 ;




5-35          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Types of Joins


       Joins that are compliant with the SQL:1999 standard
       include the following:
        • Cross joins
        • Natural joins
        • USING clause
        • Full (or two-sided) outer joins
        • Arbitrary join conditions for outer joins




5-36         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Joining Tables Using SQL:1999 Syntax


       Use a join to query data from more than one table:
       SELECT   table1.column, table2.column
       FROM     table1
       [NATURAL JOIN table2] |
       [JOIN table2 USING (column_name)] |
       [JOIN table2
         ON (table1.column_name = table2.column_name)]|
       [LEFT|RIGHT|FULL OUTER JOIN table2
         ON (table1.column_name = table2.column_name)]|
       [CROSS JOIN table2];




5-37          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating Natural Joins


       •   The NATURAL JOIN clause is based on all columns
           in the two tables that have the same name.
       •   It selects rows from the two tables that have equal
           values in all matched columns.
       •   If the columns having the same names have
           different data types, an error is returned.




5-38         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Retrieving Records with Natural Joins


       SELECT department_id, department_name,
              location_id, city
       FROM   departments
       NATURAL JOIN locations ;




5-39         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating Joins with the USING Clause


       •   If several columns have the same names but the
           data types do not match, the NATURAL JOIN clause
           can be modified with the USING clause to specify
           the columns that should be used for an equijoin.
       •   Use the USING clause to match only one column
           when more than one column matches.
       •   Do not use a table name or alias in the referenced
           columns.
       •   The NATURAL JOIN and USING clauses are
           mutually exclusive.




5-40         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Joining Column Names


       EMPLOYEES                                     DEPARTMENTS




       …                                   …
                       Foreign key              Primary key

5-41         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Retrieving Records with the USING Clause


       SELECT employees.employee_id, employees.last_name,
              departments.location_id, department_id
       FROM   employees JOIN departments
       USING (department_id) ;




       …



5-42         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Qualifying Ambiguous
                         Column Names

       •   Use table prefixes to qualify column names that
           are in multiple tables.
       •   Use table prefixes to improve performance.
       •   Use column aliases to distinguish columns that
           have identical names but reside in different tables.
       •   Do not use aliases on columns that are identified
           in the USING clause and listed elsewhere in the
           SQL statement.




5-43         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Using Table Aliases


       •   Use table aliases to simplify queries.
       •   Use table aliases to improve performance.
       SELECT e.employee_id, e.last_name,
              d.location_id, department_id
       FROM   employees e JOIN departments d
       USING (department_id) ;




5-44         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating Joins with the ON Clause


       •   The join condition for the natural join is basically
           an equijoin of all columns with the same name.
       •   Use the ON clause to specify arbitrary conditions
           or specify columns to join.
       •   The join condition is separated from other search
           conditions.
       •   The ON clause makes code easy to understand.




5-45          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Retrieving Records with the ON Clause


       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);




       …




5-46          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Self-Joins Using the ON Clause


EMPLOYEES (WORKER)                        EMPLOYEES (MANAGER)




…                                        …




         MANAGER_ID in the WORKER table is equal to
            EMPLOYEE_ID in the MANAGER table.

5-47    Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Self-Joins Using the ON Clause


       SELECT e.last_name emp, m.last_name mgr
       FROM   employees e JOIN employees m
       ON    (e.manager_id = m.employee_id);




       …




5-48         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Applying Additional Conditions
                       to a Join

       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)
       AND    e.manager_id = 149 ;




5-49         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating Three-Way Joins with the
                       ON Clause

       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;




       …


5-50            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Non-Equijoins


       EMPLOYEES                                     JOB_GRADES




                                                    Salary in the EMPLOYEES
                                                    table must be between
       …                                            lowest salary and highest
                                                    salary in the JOB_GRADES
                                                    table.

5-51         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Retrieving Records
                            with Non-Equijoins

       SELECT    e.last_name, e.salary, j.grade_level
       FROM      employees e JOIN job_grades j
       ON        e.salary
                 BETWEEN j.lowest_sal AND j.highest_sal;




       …


5-52            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Outer Joins


       DEPARTMENTS                           EMPLOYEES




                                               …

                                               There are no employees in
                                               department 190.


5-53         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
INNER Versus OUTER Joins


       •   In SQL:1999, the join of two tables returning only
           matched rows is called an inner join.
       •   A join between two tables that returns the results
           of the inner join as well as the unmatched rows
           from the left (or right) tables is called a left (or
           right) outer join.
       •   A join between two tables that returns the results
           of an inner join as well as the results of a left and
           right join is a full outer join.




5-54          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
LEFT OUTER JOIN


       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) ;




       …




5-55          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
RIGHT OUTER JOIN


       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) ;




       …




5-56          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
FULL OUTER JOIN


       SELECT e.last_name, d.department_id, d.department_name
       FROM   employees e FULL OUTER JOIN departments d
       ON   (e.department_id = d.department_id) ;




       …




5-57          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Cartesian Products


       •   A Cartesian product is formed when:
           –   A join condition is omitted
           –   A join condition is invalid
           –   All rows in the first table are joined to all rows in the
               second table
       •   To avoid a Cartesian product, always include a
           valid join condition.




5-58           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Generating a Cartesian Product

       EMPLOYEES (20 rows)                          DEPARTMENTS (8 rows)


       …




       Cartesian product:
        20 x 8 = 160 rows

                            …


5-59          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating Cross Joins


       •   The CROSS JOIN clause produces the cross-
           product of two tables.
       •   This is also called a Cartesian product between
           the two tables.

       SELECT last_name, department_name
       FROM   employees
       CROSS JOIN departments ;




       …


5-60         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Summary


       In this lesson, you should have learned how to use
       joins to display data from multiple tables by using:
        • Equijoins
        • Non-equijoins
        • Outer joins
        • Self-joins
        • Cross joins
        • Natural joins
        • Full (or two-sided) outer joins




5-61          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 5: Overview


       This practice covers the following topics:
        • Joining tables using an equijoin
        • Performing outer and self-joins
        • Adding conditions




5-62          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 5

       Q1:Click the Exhibit button to examine the structures of
       Q1:Click
       the EMPLOYEES, DEPARTMENTS, and TAX tables.




5-63          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 5
       Q1: For which situation would you use a nonequijoin query?

       A. to find the tax percentage for each of the employees

       B. to list the name, job_id, and manager name for all the
       employees

       C. to find the name, salary, and the department name of
       employees who are not working with Smith

       D. to find the number of employees working for the
       Administrative department and earning less than 4000

       E. to display name, salary, manager ID, and department name
       of all the employees, even if the employees do
       not have a department ID assigned



5-64           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 5

       Q2:Click the Exhibit button to examine the structures of
       Q2:Click
       the EMPLOYEES and TAX tables.




5-65          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 5
       Q2: You need to find the percentage tax applicable for
       each employee. Which SQL statement would you use?

       A. SELECT employee_id, salary, tax_percent
       FROM employees e JOIN tax t
       ON e.salary BETWEEN t.min_salary AND t.max_salary;

       B. SELECT employee_id, salary, tax_percent
       FROM employees e JOIN tax t
       WHERE e.salary > t.min_salary AND < t.max_salary;

       C. SELECT employee_id, salary, tax_percent
       FROM employees e JOIN tax t
       ON (MIN(e.salary) = t.min_salary
       AND MAX(e.salary) = t.max_salary);

       D. You cannot find the information because there is no
       common column between the two tables.


5-66           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 5

       Q3:Examine the structure of the EMPLOYEES and
       Q3:Examine
       DEPARTMENTS tables:




5-67          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 5

       Q3:You want to create a report displaying
       Q3:You
       employee last names, department names, and
       locations. Which query should you use?
       A. SELECT e.last_name, d. department_name, d.location_id
       FROM employees e NATURAL JOIN departments D
       USING department_id ;

       B. SELECT last_name, department_name, location_id
       FROM employees NATURAL JOIN departments
       WHERE e.department_id =d.department_id;

       C. SELECT e.last_name, d.department_name, d.location_id
       FROM employees e NATURAL JOIN departments d;

       D. SELECT e.last_name, d.department_name, d.location_id
       FROM employees e JOIN departments d USING (department_id );


5-68         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 5

       Q4:Click the Exhibit button to examine the structure of the
       EMPLOYEES, DEPARTMENTS, and LOCATIONS tables.

 Two new departments are added to your company as shown:

 DEPARTMENT_ID DEPARTMENT_NAME MGR_ID                                 LOCATION_ID
 9998          Engineering     123
 9999          Administrative                                           Boston

 You need to list the names of employees, the department IDs, the
 department names, and the cities where the departments are, even if
 there are no employees in the departments and even if the
 departments are not yet assigned to a location. You need to join the
 EMPLOYEES, DEPARTMENTS, and LOCATIONS tables to retrieve this
 information.

 Which statement do you execute to retrieve this information?


5-69          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 5

       Q4:




5-70         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 5
       A. SELECT e.last_name, d.department_id, d.department_name,
       l.city FROM departments d RIGHT OUTER JOIN employees e ON
       d.department_id = e.department_id RIGHT OUTER JOIN locations l
       ON d.location_id = l.location_id;

       B. SELECT e.last_name, d.department_id, d.department_name,
       l.city FROM departments d FULL OUTER JOIN employees e
       ON d.department_id = e.department_id FULL OUTER JOIN
       locations l ON d.location_id = l.location_id;

       C. SELECT e.last_name, d.department_id, d.department_name,
       l.city FROM departments d LEFT OUTER JOIN employees e
       ON d.department_id = e.department_id LEFT OUTER JOIN
       locations l ON d.location_id = l.location_id;

       D. SELECT last_name, department_id, department_name, city
       FROM departments d NATURAL JOIN employees e NATURAL
       JOIN locations l;


5-71           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 5

       Q5:Click the Exhibit button and examine the data in the
       EMPLOYEES and DEPARTMENTS tables.




5-72          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 5

        Q5:You want to retrieve all employees' last names, along
        with their managers' last names and their department
        names. Which query would you use?
A. SELECT last_name, manager_id, department_name FROM employees e
FULL OUTER JOIN departments d ON (e.department_id = d.department_id);

B. SELECT e.last_name, m.last_name, department_name FROM employees
e LEFT OUTER JOIN employees m on ( e.manager_id = m.employee_id)
LEFT OUTER JOIN departments d ON (e.department_id = d.department_id);

C. SELECT e.last_name, m.last_name, department_name FROM employees
e RIGHT OUTER JOIN employees m on ( e.manager_id = m.employee_id)
LEFT OUTER JOIN departments d ON (e.department_id = d.department_id);




 5-73          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 5

        Q5:


D. SELECT e.last_name, m.last_name, department_name FROM employees
e LEFT OUTER JOIN employees m on ( e.manager_id = m.employee_id)
RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id);

E. SELECT e.last_name, m.last_name, department_name FROM employees
e RIGHT OUTER JOIN employees m on ( e.manager_id = m.employee_id)
RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id);

F. SELECT last_name, manager_id, department_name FROM employees e
JOIN departments d ON (e.department_id = d.department_id) ;




 5-74         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.

More Related Content

What's hot

Les09
Les09Les09
Les02
Les02Les02
An introduction to SQLAlchemy
An introduction to SQLAlchemyAn introduction to SQLAlchemy
An introduction to SQLAlchemy
mengukagan
 
Les06
Les06Les06
Les06
Akmal Rony
 
Bassem Hussien Abd El-Hameed 14-12-2014
Bassem Hussien Abd El-Hameed 14-12-2014Bassem Hussien Abd El-Hameed 14-12-2014
Bassem Hussien Abd El-Hameed 14-12-2014
Bassem Hussien
 
Import data rahul vishwanath
Import data rahul vishwanathImport data rahul vishwanath
Import data rahul vishwanath
mohamed refaei
 
User hook implemantation sample example
User hook implemantation  sample exampleUser hook implemantation  sample example
User hook implemantation sample example
Ashish Harbhajanka
 
7 enterprise hcm information
7   enterprise hcm information7   enterprise hcm information
7 enterprise hcm information
mohamed refaei
 
12 13 jobs and positions
12 13   jobs and positions12 13   jobs and positions
12 13 jobs and positions
mohamed refaei
 
JD Edwards & Peoplesoft 1 _ Peter Bruce _ Include Work Centre error messages ...
JD Edwards & Peoplesoft 1 _ Peter Bruce _ Include Work Centre error messages ...JD Edwards & Peoplesoft 1 _ Peter Bruce _ Include Work Centre error messages ...
JD Edwards & Peoplesoft 1 _ Peter Bruce _ Include Work Centre error messages ...
InSync2011
 

What's hot (10)

Les09
Les09Les09
Les09
 
Les02
Les02Les02
Les02
 
An introduction to SQLAlchemy
An introduction to SQLAlchemyAn introduction to SQLAlchemy
An introduction to SQLAlchemy
 
Les06
Les06Les06
Les06
 
Bassem Hussien Abd El-Hameed 14-12-2014
Bassem Hussien Abd El-Hameed 14-12-2014Bassem Hussien Abd El-Hameed 14-12-2014
Bassem Hussien Abd El-Hameed 14-12-2014
 
Import data rahul vishwanath
Import data rahul vishwanathImport data rahul vishwanath
Import data rahul vishwanath
 
User hook implemantation sample example
User hook implemantation  sample exampleUser hook implemantation  sample example
User hook implemantation sample example
 
7 enterprise hcm information
7   enterprise hcm information7   enterprise hcm information
7 enterprise hcm information
 
12 13 jobs and positions
12 13   jobs and positions12 13   jobs and positions
12 13 jobs and positions
 
JD Edwards & Peoplesoft 1 _ Peter Bruce _ Include Work Centre error messages ...
JD Edwards & Peoplesoft 1 _ Peter Bruce _ Include Work Centre error messages ...JD Edwards & Peoplesoft 1 _ Peter Bruce _ Include Work Centre error messages ...
JD Edwards & Peoplesoft 1 _ Peter Bruce _ Include Work Centre error messages ...
 

Similar to Lesson05 从多表中查询数据

Les05
Les05Les05
Les05
Akmal Rony
 
Lesson08
Lesson08Lesson08
Lesson08
renguzi
 
Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句
renguzi
 
Oracle examples
Oracle examplesOracle examples
Oracle examples
MaRwa Samih AL-Amri
 
Lesson07
Lesson07Lesson07
Lesson07
renguzi
 
Les05
Les05Les05
Les02 Restricting and Sorting Data using SQL.ppt
Les02 Restricting and Sorting Data using SQL.pptLes02 Restricting and Sorting Data using SQL.ppt
Les02 Restricting and Sorting Data using SQL.ppt
DrZeeshanBhatti
 
MySQL EXPLAIN Explained-Norvald H. Ryeng
MySQL EXPLAIN Explained-Norvald H. RyengMySQL EXPLAIN Explained-Norvald H. Ryeng
MySQL EXPLAIN Explained-Norvald H. Ryeng
郁萍 王
 
Restricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseRestricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data Base
Salman Memon
 
Les02.ppt
Les02.pptLes02.ppt
Les02.ppt
gfhfghfghfgh1
 
Oracle sql joins
Oracle sql joinsOracle sql joins
Oracle sql joins
redro
 
Les04 Displaying Data from Multiple Tables.ppt
Les04 Displaying Data from Multiple Tables.pptLes04 Displaying Data from Multiple Tables.ppt
Les04 Displaying Data from Multiple Tables.ppt
DrZeeshanBhatti
 
Useful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesUseful PL/SQL Supplied Packages
Useful PL/SQL Supplied Packages
Maria Colgan
 
plsql les01
 plsql les01 plsql les01
plsql les01
sasa_eldoby
 
War of the Indices- SQL Server and Oracle
War of the Indices-  SQL Server and OracleWar of the Indices-  SQL Server and Oracle
War of the Indices- SQL Server and Oracle
Kellyn Pot'Vin-Gorman
 
ADVANCE SQL-"Sub queries"
ADVANCE SQL-"Sub queries"ADVANCE SQL-"Sub queries"
ADVANCE SQL-"Sub queries"
Ankit Surti
 
Displaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data BaseDisplaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data Base
Salman Memon
 
Les01
Les01Les01
Les01
Akmal Rony
 
Lesson10
Lesson10Lesson10
Lesson10
renguzi
 
Sharding using MySQL and PHP
Sharding using MySQL and PHPSharding using MySQL and PHP
Sharding using MySQL and PHP
Mats Kindahl
 

Similar to Lesson05 从多表中查询数据 (20)

Les05
Les05Les05
Les05
 
Lesson08
Lesson08Lesson08
Lesson08
 
Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句
 
Oracle examples
Oracle examplesOracle examples
Oracle examples
 
Lesson07
Lesson07Lesson07
Lesson07
 
Les05
Les05Les05
Les05
 
Les02 Restricting and Sorting Data using SQL.ppt
Les02 Restricting and Sorting Data using SQL.pptLes02 Restricting and Sorting Data using SQL.ppt
Les02 Restricting and Sorting Data using SQL.ppt
 
MySQL EXPLAIN Explained-Norvald H. Ryeng
MySQL EXPLAIN Explained-Norvald H. RyengMySQL EXPLAIN Explained-Norvald H. Ryeng
MySQL EXPLAIN Explained-Norvald H. Ryeng
 
Restricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseRestricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data Base
 
Les02.ppt
Les02.pptLes02.ppt
Les02.ppt
 
Oracle sql joins
Oracle sql joinsOracle sql joins
Oracle sql joins
 
Les04 Displaying Data from Multiple Tables.ppt
Les04 Displaying Data from Multiple Tables.pptLes04 Displaying Data from Multiple Tables.ppt
Les04 Displaying Data from Multiple Tables.ppt
 
Useful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesUseful PL/SQL Supplied Packages
Useful PL/SQL Supplied Packages
 
plsql les01
 plsql les01 plsql les01
plsql les01
 
War of the Indices- SQL Server and Oracle
War of the Indices-  SQL Server and OracleWar of the Indices-  SQL Server and Oracle
War of the Indices- SQL Server and Oracle
 
ADVANCE SQL-"Sub queries"
ADVANCE SQL-"Sub queries"ADVANCE SQL-"Sub queries"
ADVANCE SQL-"Sub queries"
 
Displaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data BaseDisplaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data Base
 
Les01
Les01Les01
Les01
 
Lesson10
Lesson10Lesson10
Lesson10
 
Sharding using MySQL and PHP
Sharding using MySQL and PHPSharding using MySQL and PHP
Sharding using MySQL and PHP
 

Recently uploaded

Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
TIPNGVN2
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 

Recently uploaded (20)

Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 

Lesson05 从多表中查询数据

  • 1. Oracle OCP 考试系列培训 之 1Z0-007 Lesson5 www.OracleOnLinux.cn 5-1 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 2. 5 Displaying Data from Multiple Tables 5-2 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 3. Objectives After completing this lesson, you should be able to do the following: • Write SELECT statements to access data from more than one table using equijoins and non- equijoins • Join a table to itself by using a self-join • View data that generally does not meet a join condition by using outer joins • Generate a Cartesian product of all rows from two or more tables 5-3 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 4. Obtaining Data from Multiple Tables EMPLOYEES DEPARTMENTS … … 5-4 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 5. Oracle 的多表查询 使用连接从多个表中查询数据; SELECT last_name,department_name SELECT last_name,department_name last_name,department_name last_name,department_name FROM employees,departments; FROM employees,departments; 产生笛卡尔乘积. 5-5 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 6. 连接的类型 Oracle 以前的连接 (8i SQL: 1999 and prior 90SQL): 90SQL): 适应性连接: 等值连接 -- Equijoin 交叉连接 -- Cross joins 非等值连接 -- Non-equijoin 自然连接 -- Natural joins 外连接 -- Outer join 使用Using子句的连接 自连接 -- Self join 完全外连接或者左、右外连接 5-6 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 7. 使用 Oracle 的语法连接多个表 使用连接从多个表中查询数据. SELECT SELECT table1.column, table2.column table1.column, table2.column FROM FROM table1, table2 table1, table2 WHERE WHERE table1.column1 = table2.column2; table1.column1 = table2.column2; • 在 WHERE 子句中写入连接条件. • 当多个表中有重名列时,在列的名字前加上表名作为 前缀. 5-7 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 8. 什么是等值连接? ? EMPLOYEES DEPARTMENTS … … Foreign key Primary key 5-8 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 9. 使用等值连接查询数据 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; … 5-9 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 10. 使用 AND 操作符增加查询条件 EMPLOYEES DEPARTMENTS … … 5-10 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 11. 使用 AND 操作符增加查询条件 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 AND employees.salary>10000 ; 5-11 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 12. 使用表的别名 • 使用表的别名简化了查询. • 提供虚拟数据源,自连接中更能体现. 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 e.employee_id, e.last_name, e.department_id, d.department_id, departments.location_id departments.location_id FROM employees e , departments d WHERE e.department_id = d.department_id; 5-12 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 13. 对多表作等值连接查询 EMPLOYEES DEPARTMENTS LOCATIONS … 为了连接n个表, 至少需要n-1个连接条件.例如,为了连接三 个表,至少需要两个连接条件. 5-13 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 14. 对多表作等值连接查询 EMPLOYEES DEPARTMENTS LOCATIONS JOBS JOBS col job_title for a30 col last_name for a20 col department_name for a20 set linesize 120 SELECT e.last_name,d.department_name,j.job_title,l.city FROM employees e,departments d,jobs j,locations l WHERE e.department_id=d.department_id AND e.job_id=j.job_id AND d.location_id=l.location_id; LAST_NAME DEPARTMENT_NAME JOB_TITLE CITY --------------- ------------------------------ ----------------------------------- ------------------------------ King Executive President Seattle De Haan Executive Administration Vice President Seattle Kochhar Executive Administration Vice President Seattle ...... 5-14 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 15. 非等值连接 EMPLOYEES JOB_GRADES 在 EMPLOYEES 表中所有薪水 位于JOB_GRADES JOB_GRADES JOB_GRADES表最低薪水 … 和最高薪水之间雇员的薪水信 息. . 除等值连接之外的所有连接都认为是非等值连接。 5-15 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 16. 使用非等值连接查询数据 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; … 5-16 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 17. 外连接 DEPARTMENTS EMPLOYEES … 没有雇员属于190部门. 5-17 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 18. 外连接的语法 • 为了看到那些不匹配的数据,必须使用外连接. • 外连接的操作符为 (+). (+). • 不能把连接操作符(+)同时运用在两端(99SQL支持). • 等值连接"丢失"记录,外连接则显示所有记录. SELECT table1.column, table2.column SELECT table1.column, table2.column FROM FROM table1, table2 table1, table2 WHERE table1.column(+) = table2.column; WHERE table1.column(+) = table2.column; table1.column(+) table1.column(+) SELECT SELECT table1.column, table2.column table1.column, table2.column FROM FROM table1, table2 table1, table2 WHERE WHERE table1.column = table2.column(+); table1.column = table2.column(+) ; (+); table2.column(+) table2.column(+) (+); 5-18 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 19. 使用外连接 SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id(+) = d.department_id ; … 5-19 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 20. 自连接 EMPLOYEES (WORKER) EMPLOYEES (MANAGER) … … WORKER表中的MANAGER_ID 等于 MANAGER 表中的 WORKER MANAGER_ID EMPLOYEE_ID. 5-20 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 21. 对一张表作自连接查询 SELECT worker.last_name || ' works for ' || manager.last_name FROM employees worker, employees manager WHERE worker.manager_id = manager.employee_id ; … 员工的管理者编号就是管理者作为员工的员工编号 5-21 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 22. 使用 SQL: 1999 语法执行表的连接 使用连接从多个表中查询数据. SELECT SELECT table1.column, table2.column table1.column, table2.column FROM FROM table1 table1 [CROSS JOIN table2] | [CROSS JOIN table2] | [NATURAL JOIN table2] | [NATURAL JOIN table2] | [JOIN table2 USING (column_name)] | [JOIN table2 USING (column_name)] | [JOIN table2 [JOIN table2 ON(table1.column_name = table2.column_name)] | ON(table1.column_name = table2.column_name)] | [LEFT|RIGHT|FULL OUTER JOIN table2 [LEFT|RIGHT|FULL OUTER JOIN table2 ON (table1.column_name = table2.column_name)]; ON (table1.column_name = table2.column_name)]; 5-22 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 23. 建立交叉连接 • CROSS JOIN 子句产生两个表的交叉连接. • 产生的结果等于两个表执行笛卡尔乘积. SELECT last_name, department_name FROM employees CROSS JOIN departments ; … 5-23 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 24. 建立自然连接 • NATURAL JOIN 子句基于两个表中列名完全相同的多 个列产生连接. • 从两个表中选出连接列的值相等的所有行. • 如果两个列的名称相同,但是具有不同的数据类型,则 查询会返回一个错误. – 字段名同,含义不同;(不想连接却连上了) – 字段名不同,含义同;(想连却连不上) – 字段名同,含义同;(不可以显示指定不连) – 不能做非等值连接; 5-24 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 25. 用自然连接查询数据 SELECT department_id, department_name, location_id, city FROM departments NATURAL JOIN locations ; 5-25 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 26. 使用 USING 子句建立连接 • 如果某些列有相同的名称但数据类型不匹配,自然连接 将出错,可以在自然连接的 NATURAL JOIN 子句上 使用 USING 子句来设置用于等值连接的列. • 不要在引用列上使用表名或者别名作为前缀. • NATURAL JOIN 与 USING USING子句是相互独立的. – 能解决同名不同意的问题; – 解决不了同意不同名的问题; 5-26 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 27. 使用 USING 子句查询数据 SELECT e.employee_id, e.last_name, d.location_id FROM employees e JOIN departments d USING (department_id) ; … 5-27 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 28. 使用ON ON ON子句建立连接 • 自然连接的条件是基于表中所有同名列的等值连接. • 为了设置任意的连接条件或者指定连接的列,需要使 用ON ON子句. ON • 连接条件与其它的查询条件分开书写. • 使用ON 子句使查询语句更容易理解. ON 5-28 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 29. 使用 ON 子句查询数据 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); … 5-29 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 30. 使用ON ON子句建立Three-Way 连接 ON Three-Way 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; … 5-30 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 31. INNER 连接与OUTER 连接的对比 OUTER • 在SQL: 1999中, 两个表的连接只返回匹配行的被叫做 内连接. • 两个表的连接结果既包括了内连接,又包括了不匹配 左(右)边表的结果集,也就是左(右)外连接. • 两个表的连接结果既包含了内连接的结果,也包含了 左右外连接的结果,被叫做完全连接. 5-31 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 32. 左外连接 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) ; … 5-32 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 33. 右外连接 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) ; … 5-33 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 34. 完全外连接 SELECT e.last_name, e.department_id, d.department_name FROM employees e FULL OUTER JOIN departments d ON (e.department_id = d.department_id) ; … 注意完全外连接的执行顺序? 5-34 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 35. 增加其他的查询条件 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) AND e.manager_id = 149 ; 5-35 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 36. Types of Joins Joins that are compliant with the SQL:1999 standard include the following: • Cross joins • Natural joins • USING clause • Full (or two-sided) outer joins • Arbitrary join conditions for outer joins 5-36 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 37. Joining Tables Using SQL:1999 Syntax Use a join to query data from more than one table: SELECT table1.column, table2.column FROM table1 [NATURAL JOIN table2] | [JOIN table2 USING (column_name)] | [JOIN table2 ON (table1.column_name = table2.column_name)]| [LEFT|RIGHT|FULL OUTER JOIN table2 ON (table1.column_name = table2.column_name)]| [CROSS JOIN table2]; 5-37 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 38. Creating Natural Joins • The NATURAL JOIN clause is based on all columns in the two tables that have the same name. • It selects rows from the two tables that have equal values in all matched columns. • If the columns having the same names have different data types, an error is returned. 5-38 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 39. Retrieving Records with Natural Joins SELECT department_id, department_name, location_id, city FROM departments NATURAL JOIN locations ; 5-39 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 40. Creating Joins with the USING Clause • If several columns have the same names but the data types do not match, the NATURAL JOIN clause can be modified with the USING clause to specify the columns that should be used for an equijoin. • Use the USING clause to match only one column when more than one column matches. • Do not use a table name or alias in the referenced columns. • The NATURAL JOIN and USING clauses are mutually exclusive. 5-40 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 41. Joining Column Names EMPLOYEES DEPARTMENTS … … Foreign key Primary key 5-41 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 42. Retrieving Records with the USING Clause SELECT employees.employee_id, employees.last_name, departments.location_id, department_id FROM employees JOIN departments USING (department_id) ; … 5-42 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 43. Qualifying Ambiguous Column Names • Use table prefixes to qualify column names that are in multiple tables. • Use table prefixes to improve performance. • Use column aliases to distinguish columns that have identical names but reside in different tables. • Do not use aliases on columns that are identified in the USING clause and listed elsewhere in the SQL statement. 5-43 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 44. Using Table Aliases • Use table aliases to simplify queries. • Use table aliases to improve performance. SELECT e.employee_id, e.last_name, d.location_id, department_id FROM employees e JOIN departments d USING (department_id) ; 5-44 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 45. Creating Joins with the ON Clause • The join condition for the natural join is basically an equijoin of all columns with the same name. • Use the ON clause to specify arbitrary conditions or specify columns to join. • The join condition is separated from other search conditions. • The ON clause makes code easy to understand. 5-45 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 46. Retrieving Records with the ON Clause 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); … 5-46 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 47. Self-Joins Using the ON Clause EMPLOYEES (WORKER) EMPLOYEES (MANAGER) … … MANAGER_ID in the WORKER table is equal to EMPLOYEE_ID in the MANAGER table. 5-47 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 48. Self-Joins Using the ON Clause SELECT e.last_name emp, m.last_name mgr FROM employees e JOIN employees m ON (e.manager_id = m.employee_id); … 5-48 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 49. Applying Additional Conditions to a Join 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) AND e.manager_id = 149 ; 5-49 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 50. Creating Three-Way Joins with the ON Clause 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; … 5-50 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 51. Non-Equijoins EMPLOYEES JOB_GRADES Salary in the EMPLOYEES table must be between … lowest salary and highest salary in the JOB_GRADES table. 5-51 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 52. Retrieving Records with Non-Equijoins SELECT e.last_name, e.salary, j.grade_level FROM employees e JOIN job_grades j ON e.salary BETWEEN j.lowest_sal AND j.highest_sal; … 5-52 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 53. Outer Joins DEPARTMENTS EMPLOYEES … There are no employees in department 190. 5-53 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 54. INNER Versus OUTER Joins • In SQL:1999, the join of two tables returning only matched rows is called an inner join. • A join between two tables that returns the results of the inner join as well as the unmatched rows from the left (or right) tables is called a left (or right) outer join. • A join between two tables that returns the results of an inner join as well as the results of a left and right join is a full outer join. 5-54 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 55. LEFT OUTER JOIN 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) ; … 5-55 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 56. RIGHT OUTER JOIN 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) ; … 5-56 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 57. FULL OUTER JOIN SELECT e.last_name, d.department_id, d.department_name FROM employees e FULL OUTER JOIN departments d ON (e.department_id = d.department_id) ; … 5-57 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 58. Cartesian Products • A Cartesian product is formed when: – A join condition is omitted – A join condition is invalid – All rows in the first table are joined to all rows in the second table • To avoid a Cartesian product, always include a valid join condition. 5-58 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 59. Generating a Cartesian Product EMPLOYEES (20 rows) DEPARTMENTS (8 rows) … Cartesian product: 20 x 8 = 160 rows … 5-59 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 60. Creating Cross Joins • The CROSS JOIN clause produces the cross- product of two tables. • This is also called a Cartesian product between the two tables. SELECT last_name, department_name FROM employees CROSS JOIN departments ; … 5-60 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 61. Summary In this lesson, you should have learned how to use joins to display data from multiple tables by using: • Equijoins • Non-equijoins • Outer joins • Self-joins • Cross joins • Natural joins • Full (or two-sided) outer joins 5-61 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 62. Practice 5: Overview This practice covers the following topics: • Joining tables using an equijoin • Performing outer and self-joins • Adding conditions 5-62 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 63. Practice 5 Q1:Click the Exhibit button to examine the structures of Q1:Click the EMPLOYEES, DEPARTMENTS, and TAX tables. 5-63 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 64. Practice 5 Q1: For which situation would you use a nonequijoin query? A. to find the tax percentage for each of the employees B. to list the name, job_id, and manager name for all the employees C. to find the name, salary, and the department name of employees who are not working with Smith D. to find the number of employees working for the Administrative department and earning less than 4000 E. to display name, salary, manager ID, and department name of all the employees, even if the employees do not have a department ID assigned 5-64 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 65. Practice 5 Q2:Click the Exhibit button to examine the structures of Q2:Click the EMPLOYEES and TAX tables. 5-65 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 66. Practice 5 Q2: You need to find the percentage tax applicable for each employee. Which SQL statement would you use? A. SELECT employee_id, salary, tax_percent FROM employees e JOIN tax t ON e.salary BETWEEN t.min_salary AND t.max_salary; B. SELECT employee_id, salary, tax_percent FROM employees e JOIN tax t WHERE e.salary > t.min_salary AND < t.max_salary; C. SELECT employee_id, salary, tax_percent FROM employees e JOIN tax t ON (MIN(e.salary) = t.min_salary AND MAX(e.salary) = t.max_salary); D. You cannot find the information because there is no common column between the two tables. 5-66 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 67. Practice 5 Q3:Examine the structure of the EMPLOYEES and Q3:Examine DEPARTMENTS tables: 5-67 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 68. Practice 5 Q3:You want to create a report displaying Q3:You employee last names, department names, and locations. Which query should you use? A. SELECT e.last_name, d. department_name, d.location_id FROM employees e NATURAL JOIN departments D USING department_id ; B. SELECT last_name, department_name, location_id FROM employees NATURAL JOIN departments WHERE e.department_id =d.department_id; C. SELECT e.last_name, d.department_name, d.location_id FROM employees e NATURAL JOIN departments d; D. SELECT e.last_name, d.department_name, d.location_id FROM employees e JOIN departments d USING (department_id ); 5-68 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 69. Practice 5 Q4:Click the Exhibit button to examine the structure of the EMPLOYEES, DEPARTMENTS, and LOCATIONS tables. Two new departments are added to your company as shown: DEPARTMENT_ID DEPARTMENT_NAME MGR_ID LOCATION_ID 9998 Engineering 123 9999 Administrative Boston You need to list the names of employees, the department IDs, the department names, and the cities where the departments are, even if there are no employees in the departments and even if the departments are not yet assigned to a location. You need to join the EMPLOYEES, DEPARTMENTS, and LOCATIONS tables to retrieve this information. Which statement do you execute to retrieve this information? 5-69 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 70. Practice 5 Q4: 5-70 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 71. Practice 5 A. SELECT e.last_name, d.department_id, d.department_name, l.city FROM departments d RIGHT OUTER JOIN employees e ON d.department_id = e.department_id RIGHT OUTER JOIN locations l ON d.location_id = l.location_id; B. SELECT e.last_name, d.department_id, d.department_name, l.city FROM departments d FULL OUTER JOIN employees e ON d.department_id = e.department_id FULL OUTER JOIN locations l ON d.location_id = l.location_id; C. SELECT e.last_name, d.department_id, d.department_name, l.city FROM departments d LEFT OUTER JOIN employees e ON d.department_id = e.department_id LEFT OUTER JOIN locations l ON d.location_id = l.location_id; D. SELECT last_name, department_id, department_name, city FROM departments d NATURAL JOIN employees e NATURAL JOIN locations l; 5-71 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 72. Practice 5 Q5:Click the Exhibit button and examine the data in the EMPLOYEES and DEPARTMENTS tables. 5-72 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 73. Practice 5 Q5:You want to retrieve all employees' last names, along with their managers' last names and their department names. Which query would you use? A. SELECT last_name, manager_id, department_name FROM employees e FULL OUTER JOIN departments d ON (e.department_id = d.department_id); B. SELECT e.last_name, m.last_name, department_name FROM employees e LEFT OUTER JOIN employees m on ( e.manager_id = m.employee_id) LEFT OUTER JOIN departments d ON (e.department_id = d.department_id); C. SELECT e.last_name, m.last_name, department_name FROM employees e RIGHT OUTER JOIN employees m on ( e.manager_id = m.employee_id) LEFT OUTER JOIN departments d ON (e.department_id = d.department_id); 5-73 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 74. Practice 5 Q5: D. SELECT e.last_name, m.last_name, department_name FROM employees e LEFT OUTER JOIN employees m on ( e.manager_id = m.employee_id) RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id); E. SELECT e.last_name, m.last_name, department_name FROM employees e RIGHT OUTER JOIN employees m on ( e.manager_id = m.employee_id) RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id); F. SELECT last_name, manager_id, department_name FROM employees e JOIN departments d ON (e.department_id = d.department_id) ; 5-74 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.