Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć2... Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć4... Introduction to Oracle: SQL and PL/SQL Using P
Trang 1Displaying Data from Multiple
Tables4
Trang 2Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć2
Trang 3This 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 equalityand non-equality joins
D View data that would not normally meet a join condition by using outer joins
D Join a table to itself
Trang 4Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć4
Trang 5When 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 commonvalues existing in corresponding columns, that is to say primary and foreign keycolumns
There are two main types of join conditions:
For more information about set operators, attend
Advanced SQL and SQL*Plus course.
Trang 6Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć6
Trang 7What 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 rarelyuseful You should always include a valid join condition in a WHERE clause, unlessyou have a specific need to combine all rows from all tables
SQL> SELECT name, last_name
300 rows selected
Trang 8Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć8
Trang 9Simple Join Query
To display data from two or more related tables, write a simple join condition in theWHERE clause
Syntax
SELECT table.column, table.column
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
to uniquely identify each row
For more information, see
Oracle7 Server SQL Language Reference Manual, “SELECT.”
Trang 10Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć10
Server
ÉÉÉÉ
Trang 11Simple 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
4 WHERE s_emp.dept_id = s_dept.id;
LAST_NAME DEPT_ID NAME
Trang 12Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć12
Trang 13Simple Join Query continued
Qualifying Ambiguous Column Names
You need to qualify the names of the columns in the WHERE clause with the tablename to avoid ambiguity Without the table prefixes, the ID column could be fromeither the S_DEPT or the S_EMP table It is necessary to add the table prefix toexecute 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 thetable prefix
Example
Display the department number, region number, and region name for all departments
SQL> SELECT s_dept.id ”Department ID”,
5 WHERE s_dept.region_id = s_region.id;
Department ID Region ID Region Name
Trang 14Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć14
Server
ÉÉ ÉÉ
Trang 15Simple 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 additionalconditions 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,
4 WHERE s_emp.dept_id = s_dept.id
LAST_NAME DEPT_ID NAME
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
Trang 16Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć16
Trang 17Using 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 columnreference 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”,
D Table aliases should be meaningful
D The table alias is only valid for the current SELECT statement
Trang 18Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć18
Trang 19The 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
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
Trang 20Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć20
Trang 21Returning 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, SweetRock 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-deficienttable can be joined
Syntax
SELECT table.column, table.column
WHERE table1.column = table2.column(+);
or
SELECT table.column, table.column
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, butnot on both sides Place the outer join symbolfollowing the name of the table without thematching rows
Trang 22Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć22
Server
ÉÉ É
Trang 23Returning Records with No Direct Match continued
Example
Display the sales representative name and employee number and the customer namefor all customers Include the customer name even if the customer has not beenassigned a sales representative
SQL> SELECT e.last_name, e.id, c.name
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 nodirect match in the other table
D A condition involving an outer join may not use the IN operator or be linked toanother condition by the OR operator
Trang 24Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć24
Server
ÉÉ É
Trang 25Joining a Table to Itself
You can join a table to itself by using table aliases to simulate as if the table were twoseparate tables This allows rows in a table to be joined to rows in the same table
Display the names of employees and their respective managers
SQL> SELECT worker.last_name||’ works for ’||
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
Trang 26Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć26
Trang 27There are multiple ways to join tables The common thread, though, is that you want
to link them through a condition in the WHERE clause The method you choose will
be based on the required result and the data structures you are using
Syntax
SELECT table.column, table.column
where: table.column denotes a table and column from which data is
retrieved
table1.column1 = is the condition that joins (or relates)
table2.column2 the tables together
Trang 28Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć28
Trang 29Practice Overview
This practice is intended to give you practical experience extracting data from morethan one table You will be required to join and restrict rows in the WHERE clause
Practice Contents
D Joining tables using an equijoin
D Performing outer and self joins
D Adding additional conditions
Trang 30Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć30
Trang 32Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć32
-Magee Sales North America
Giljum Sales South America
Sedeghi Sales Africa / Middle East
Nguyen Sales Asia
Dumas Sales Europe
3. Display the employee name and department name for Smith
-Grand Prix Bicycle Tires 30421 15
Pro Curling Bar 40422 30
Prostar 10 Pound Weight 41010 20
Prostar 100 Pound Weight 41100 35
Major League Baseball 50169 40
Griffey Glove 50417 27
Cabrera Bat 50530 50
7 rows selected
Trang 34Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć34
If you have time, complete the following exercises
6. Display the customer number, customer name, and order number of all customers and their orders Display the customer number and name, even if they have not placed an order
Customer ID Customer Name Order ID
-
201 Unisports 97
202 Simms Atheletics 98
203 Delhi Sports 99
204 Womansport 100
204 Womansport 111
205 Kam’s Sporting Goods 101
206 Sportique 102
207 Sweet Rock Sports
208 Muench Sports 103
208 Muench Sports 104
209 Beisbol Si! 105
210 Futbol Sonora 106
210 Futbol Sonora 112
211 Kuhn’s Sports 107
212 Hamada Sport 108
213 Big John’s Sports Emporium 109
214 Ojibway Retail 110
215 Sporta Russia
18 rows selected
Trang 36Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć36
8. Modify the solution to exercise 7 to also display Velasquez, who has no manager
Trang 3726 rows selected.
Trang 38Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 4Ć38