Tải bản đầy đủ (.pdf) (38 trang)

Tài liệu displaying data from multiple tables pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (245.21 KB, 38 trang )

Displaying Data from Multiple
Tables
4
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder4Ć2
Schedule: Timing Topic
40 minutes Lecture
50 minutes Practice
90 minutes Total
Class Management Note:
Files required for lesson are:
Demonstration: l4cart.sql, l4region.sql, l4ejoin.sql, l4ojoin.sql
Practice: None
Displaying Data from Multiple Tables 4Ć3
Objectives
This lesson will cover how to obtain data from more than one table, using the
many different methods available.
At the end of this lesson, you should be able to
D Write SELECT statements to access data from more than one table using equality
and non-equality joins.
D View data that would not normally meet a join condition by using outer joins.
D Join a table to itself.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder4Ć4
Displaying Data from Multiple Tables 4Ć5
Overview
When data from more than one table in the database is required, a join condition is
used. Rows in one table may be joined to rows in another table according to common
values existing in corresponding columns, that is to say primary and foreign key
columns.
There are two main types of join conditions:
D Equijoins
D Non-equijoins


Additional join methods include the following:
D Outer joins
D Self joins
D Set operators
For more information about set operators, attend
Advanced SQL and SQL*Plus course.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder4Ć6
Class Management Note:
DEMO: l4cart.sql
PURPOSE: Point out to students that all rows are being joined since there is
no WHERE clause to join together the two tables.
Displaying Data from Multiple Tables 4Ć7
What Is a Cartesian Product?
When a join condition is invalid or omitted completely, the result is a Cartesian
Product, in which all combinations of rows will be displayed. All rows in the first
table are joined to all rows in the second table.
And Why Should You Care?
A Cartesian product tends to generate a large number of rows, and its result is rarely
useful. You should always include a valid join condition in a WHERE clause, unless
you have a specific need to combine all rows from all tables.
SQL> SELECT name, last_name
2 FROM s_dept, s_emp;

300 rows selected.
Class Management Note:
The S_EMP table contains 25 rows. The S_DEPT table contains 12 rows.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder4Ć8
Displaying Data from Multiple Tables 4Ć9
Simple Join Query
To display data from two or more related tables, write a simple join condition in the

WHERE clause.
Syntax
SELECT table.column, table.column
FROM table1, table2
WHERE table1.column1 = table2.column2;
where: table.column denotes the table and column from which data is
retrieved.
table1.column1 = is the condition that joins (or relates)
table2.column2 the tables together.
Guidelines
D When writing a SELECT statement that joins tables, precede the column name
with the table name for clarity and to enhance database access.
D If the same column name appears in more than one table, then the column name
must be prefixed with the table name.
D To join tables together, you need a minimum of the number of join conditions
summarized as the number of tables minus one. Therefore, to join four tables, a
minimum of three joins would be required. This rule may not apply if your table
has a concatenated primary key, in which case more than one column is required
to uniquely identify each row.
For more information, see
Oracle7 Server SQL Language Reference Manual, “SELECT.”
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder4Ć10
Server
Displaying Data from Multiple Tables 4Ć11
Simple Join Query continued
Equijoin
In order to determine the name of an employee’s department, you compare the value
in the DEPT_ID column in the S_EMP table with the ID values in the S_DEPT table.
The relationship between the S_EMP and S_DEPT tables is an equijoin, that is
values in the DEPT_ID column on both tables must be equal. Frequently, these

columns are primary and foreign key complements.
Example
Join together the employee and department tables to display the employee name,
department number, and department name.
SQL> SELECT s_emp.last_name, s_emp.dept_id,
2 s_dept.name
3 FROM s_emp, s_dept
4 WHERE s_emp.dept_id = s_dept.id;
LAST_NAME DEPT_ID NAME

Velasquez 50 Administration
Ngao 41 Operations
Nagayama 31 Sales
Quick-To-See 10 Finance
Ropeburn 50 Administration
Urguhart 41 Operations
Menchu 42 Operations
Biri 43 Operations
Catchpole 44 Operations
Havel 45 Operations
Magee 31 Sales
Giljum 32 Sales
Sedeghi 33 Sales

25 rows selected.
Every employee now has their respective department name displayed. The rows of
the S_EMP table are combined with the rows of the S_DEPT table, and rows are only
returned if the values of S_EMP.DEPT_ID and S_DEPT.ID are equal.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder4Ć12
Class Management Note:

DEMO: l4region.sql
PURPOSE: This script contains no aliases for the SELECT clause.
Compare this to the example on the facing page to see that the aliases are
useful for labelling columns.
Displaying Data from Multiple Tables 4Ć13
Simple Join Query continued
Qualifying Ambiguous Column Names
You need to qualify the names of the columns in the WHERE clause with the table
name to avoid ambiguity. Without the table prefixes, the ID column could be from
either the S_DEPT or the S_EMP table. It is necessary to add the table prefix to
execute your query.
If there are no names that are the same between the two tables, then there is no need
to qualify the columns. However, you will gain improved performance by using the
table prefix.
Example
Display the department number, region number, and region name for all departments.
SQL> SELECT s_dept.id ”Department ID”,
2 s_region.id ”Region ID”,
3 s_region.name ”Region Name”
4 FROM s_dept, s_region
5 WHERE s_dept.region_id = s_region.id;
Department ID Region ID Region Name

10 3 Africa / Middle East
31 1 North America
32 2 South America
33 3 Africa / Middle East
34 4 Asia
35 5 Europe
41 1 North America

42 2 South America
43 3 Africa / Middle East
44 4 Asia
45 5 Europe
50 1 North America
12 rows selected.
The requirement to qualify ambiguous column names is also applicable to columns
that may be ambiguous in a SELECT or ORDER BY clause.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder4Ć14
Server
Displaying Data from Multiple Tables 4Ć15
Simple Join Query continued
Additional Search Conditions
In addition to the join, you may have additional criteria for your WHERE clause.
Since the join is required to obtain the matches, you need to add your additional
conditions by using the AND operator. Table aliases help to keep SQL code smaller,
therefore using less memory.
Example
Display employee Menchu’s last name, department number, and department name.
SQL> SELECT s_emp.last_name, s_emp.dept_id,
2 s_dept.name
3 FROM s_emp, s_dept
4 WHERE s_emp.dept_id = s_dept.id
5 AND INITCAP(s_emp.last_name) = ’Menchu’;
LAST_NAME DEPT_ID NAME

Menchu 42 Operations
Display the last name, region name, and commission percent of all employees who
earn a commission.
SQL> SELECT s_emp.last_name, s_region.name,

2 s_emp.commission_pct
3 FROM s_emp, s_dept, s_region
4 WHERE s_emp.dept_id = s_dept.id
5 AND s_dept.region_id = s_region.id
6 AND s_emp.commission_pct > 0;
LAST_NAME NAME COMMISSION_PCT

Magee North America 10
Giljum South America 12.5
Sedeghi Africa / Middle East 10
Nguyen Asia 15
Dumas Europe 17.5
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder4Ć16
Displaying Data from Multiple Tables 4Ć17
Using Table Aliases
Qualifying column names with table names can be very time consuming, particularly
if table names are lengthy. Use table aliases instead. Like column aliases, table
aliases are a method of giving the table another name for the purpose of the SELECT
statement. Once you use the table alias, you must continue to qualify every column
reference with the table alias.
Example
Display the customer name, region number, and region name for all customers.
Provide column aliases, and use a table alias to shorten the table references.
SQL> SELECT c.name ”Customer Name”,
2 c.region_id ”Region ID”,
3 r.name ”Region Name”
4 FROM s_customer c, s_region r
5 WHERE c.region_id = r.id;
Guidelines
D Table aliases can be up to 30 characters in length, but the shorter they are the

better.
D If a table alias is used for a particular table name in the FROM clause, then that
table alias must be substituted for the table name throughout the SELECT
statement.
D Table aliases should be meaningful.
D The table alias is only valid for the current SELECT statement.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder4Ć18
Displaying Data from Multiple Tables 4Ć19
NonĆEquijoin
The relationship between the EMP and SALGRADE tables is a non-equijoin, in that
no column in EMP corresponds directly to a column in SALGRADE. The
relationship is obtained using an operator other than equal (=).
Example
Create a non-equijoin to evaluate an employee’s salary grade. The salary must be
between any pair of the low and high salary ranges.
SQL> SELECT e.ename, e.job, e.sal, s.grade
2 FROM emp e, salgrade s
3 WHERE e.sal BETWEEN s.losal AND s.hisal;
ENAME JOB SAL GRADE

SMITH CLERK 800.00 1
ADAMS CLERK 1,100.00 1
JAMES CLERK 950.00 1
WARD SALESMAN 1,250.00 2
MARTIN SALESMAN 1,250.00 2
MILLER CLERK 1,300.00 2
ALLEN SALESMAN 1,600.00 3
TURNER SALESMAN 1,500.00 3
JONES MANAGER 2,975.00 4
BLAKE MANAGER 2,850.00 4

CLARK MANAGER 2,450.00 4
SCOTT ANALYST 3,000.00 4
FORD ANALYST 3,000.00 4
KING PRESIDENT 5,000.00 5
14 rows selected.
Other operators such as <= and >= could be used, however BETWEEN is the
simplest. Remember to specify the low value first and the high value last when using
BETWEEN. Table aliases have been specified for performance reasons, not because
of possible ambiguity.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder4Ć20
Class Management Note:
DEMO: l4ejoin.sql
PURPOSE: Show that only 14 of the 15 customers appear. Sweet Rock
Sports is not in this list because it has no sales representative.
Class Management Note:
Students might ask you how to code with an outer join on both sides. This is
possible with the UNION operator, which is not addressed in this course.
Displaying Data from Multiple Tables 4Ć21
Returning Records with No Direct Match
If a row does not satisfy a join condition, then the row will not appear in the query
result. For example, in the equijoin condition of S_EMP and S_CUSTOMER, Sweet
Rock Sports does not appear because there is no sales representative for that
customer.
Outer Join
The missing row(s) can be returned if an outer join operator is used in the join
condition. The operator is a plus sign enclosed in parentheses (+), and is placed on
the “side” of the join that is deficient in information. The operator has the effect of
creating one or more NULL rows, to which one or more rows from the non-deficient
table can be joined.
Syntax

SELECT table.column, table.column
FROM table1, table2
WHERE table1.column = table2.column(+);
or
SELECT table.column, table.column
FROM table1, table2
WHERE table1.column(+) = table2.column;
where: table1.column = is the condition that joins (or relates) the tables
table2.column together.
(+) is the outer join symbol; it can be placed on
either side of the WHERE clause condition, but
not on both sides. Place the outer join symbol
following the name of the table without the
matching rows.
Class Management Note:
Note for page 4-22.
DEMO: l4ojoin.sql
PURPOSE: Show how the outer join symbol on the S_EMP side results in
Sweet Rock Sports appearing although there is still no sales representative.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder4Ć22
Server
Displaying Data from Multiple Tables 4Ć23
Returning Records with No Direct Match continued
Example
Display the sales representative name and employee number and the customer name
for all customers. Include the customer name even if the customer has not been
assigned a sales representative.
SQL> SELECT e.last_name, e.id, c.name
2 FROM s_emp e, s_customer c
3 WHERE e.id (+) = c.sales_rep_id

4 ORDER BY e.id;
LAST_NAME ID NAME
–––––––– ––– ––––––––––––––––––––––––––––––––––––
Magee 11 Womansport
Magee 11 Beisbol Si!
Magee 11 Ojibway Retail
Magee 11 Big John’s Sports Emporium
Giljum 12 Unisports
Giljum 12 Futbol Sonora
Sedeghi 13 Hamada Sport
Nguyen 14 Simms Atheletics
Nguyen 14 Delhi Sports
Dumas 15 Kam’s Sporting Goods
Dumas 15 Sportique
Dumas 15 Muench Sports
Dumas 15 Sporta Russia
Dumas 15 Kuhn’s Sports
Sweet Rock Sports
15 rows selected.
Outer Join Restrictions
D The outer join operator can only appear on one side of the expression—the side
that has information missing. It returns those rows from one table which have no
direct match in the other table.
D A condition involving an outer join may not use the IN operator or be linked to
another condition by the OR operator.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder4Ć24
Server
Displaying Data from Multiple Tables 4Ć25
Joining a Table to Itself
You can join a table to itself by using table aliases to simulate as if the table were two

separate tables. This allows rows in a table to be joined to rows in the same table.
Self Join
In order to simulate two tables in the FROM clause, the example contains an alias for
the same table, S_EMP. This is an example of good naming conventions.
In this example, the WHERE clause contains the join that means “where a worker’s
manager number matches the employee number for the manager.”
Example
Display the names of employees and their respective managers.
SQL> SELECT worker.last_name||’ works for ’||
2 manager.last_name
3 FROM s_emp worker, s_emp manager
4 WHERE worker.manager_id = manager.id;
Ngao works for Velasquez
Nagayama works for Velasquez
Quick-To-See works for Velasquez
Ropeburn works for Velasquez
Urguhart works for Ngao
Menchu works for Ngao
Biri works for Ngao
Catchpole works for Ngao
Havel works for Ngao
Magee works for Nagayama
Giljum works for Nagayama
Sedeghi works for Nagayama
Nguyen works for Nagayama
Dumas works for Nagayama

24 rows selected.
Class Management Note:
See note on page 4-26.

×