Sie sind auf Seite 1von 48

CHAPTER 6:

ADVANCED SQL
(PART I)

Modern Database Management


12th Edition
Jeff Hoffer, Ramesh Venkataraman,
Heikki Topi

Copyright © 2016 Pearson Education, Inc.


OBJECTIVES
 Define terms
 Write single and multiple table SQL
queries
 Define and use three types of joins

 Write noncorrelated and correlated subqueries


 Understand and use SQL in procedural languages (e.g. MS SQL)

Copyright © 2016 Pearson Education, Inc. 6-2


PROCESSING MULTIPLE TABLES – WHY JOIN?
 When the fields needed are from different
tables
 Those “different tables” must possess logical
relationships for their fields to be extracted

Copyright © 2016 Pearson Education, Inc. 6-3


PROCESSING MULTIPLE TABLES
 Join–a relational operation that causes two or
more tables with a common domain to be combined
into a single table or view [for data retrieval]
 Equi-join–a join in which the joining condition is
based on equality between values in the common
columns; common columns appear redundantly in
the result table
 Natural join–an equi-join in which one of the
duplicate columns is eliminated in the result table
The common columns in joined tables are usually the
primary key of the dominant table and the foreign key of
the dependent table in 1:M relationships
P.252: No matter what form of JOIN you are using,
there should be one ON or WHERE specification for
Copyright © 2016 Pearson Education, Inc. 6-4
each pair of tables being joined. – “Join conditions”
PROCESSING MULTIPLE TABLES–JOINS
 INNER JOIN

 The kind of join that is most commonly


performed. Example:
 FROM Table1 INNER JOIN Table2 ON
Table1.PK = Table2.FK
 The key word “INNER” can be omitted:
 FROM Table1 JOIN Table2 ON
Table1.PK = Table2.FK
P. 254, first half

Copyright © 2016 Pearson Education, Inc. 6-5


PROCESSING MULTIPLE TABLES– 6

JOINS
 Outer join–a join in which
 rows that do not have matching values in
common columns are nonetheless
 included in the result table
 (as opposed to inner join, in which rows must
have matching values in order to appear in
the result table)

 Union join–includes all columns from each


table in the join, and an instance for each row of
each table
 Illustration using “abstract examples”
Copyright © 2016 Pearson Education, Inc. 6-6
Figure 6-2
Visualization of different join types with results returned
in shaded area

Right Outer Join

Copyright © 2016 Pearson Education, Inc. 6-7


THE FOLLOWING SLIDES INVOLVE QUERIES
OPERATING ON TABLES FROM THIS ENTERPRISE
DATA MODEL
(from Chapter 1, Figure 1-3)

Copyright © 2016 Pearson Education, Inc. 6-8


Figure 6-1 Pine Valley Furniture Company Customer_T and
Order_T tables with pointers from customers to their orders

•Customer_T and Order_T are 1:M


•These tables are used in queries that follow
Copyright © 2016 Pearson Education, Inc.
SPECIFYING JOINS IN SQL
 Join conditions may be specified in
 WHERE clause: Easier to use
Need parentheses; has
 FROM clause: unintended outcome if not done
carefully – caution!!!
(DIScouraged)
 Ineither case, each contains a column that
shares a common domain with the other (PK-
FK)
 N tables need __________ join conditions

 There should be one PK-FK equality


specification for each pair of tables being
joined (P. 252) – “Join conditions”
Copyright © 2016 Pearson Education, Inc. 6-10
SPECIFYING JOINS IN SQL (CONT)
 Join conditions may be specified
 In WHERE clause:
WHERE PK1=FK2 and PK2=FK3 and
Easy;
PK3=FK4
recommended
Simply state the N-1 join conditions for
the N-1 pairs of PK-FK for the N tables
involved
 In FROM clause:
FROM ((Table1 JOIN Table2 Complex; error-
ON PK1=FK2)
JOIN Table 3 ON PK2=FK3) prone;
JOIN Table 4 ON PK3=FK4 discouraged for
More complicated;
now
Copyright © 2016 Pearson Education, Inc. 6-11
EQUI-JOIN EXAMPLE
 For each customer who placed an order, what is
the customer‟s name and order number?
Fields that
appear in
only one
table does
not need
table
identificatio
n
 Structure:
 FROM Table1, Table2
 WHERE Table1.PK = Table2.FK

Copyright © 2016 Pearson Education, Inc. 6-12


EQUI-JOIN EXAMPLE

SELECT E.EmpNo, E.EName, E.DeptNo,


D.DeptNo, D.Loc
FROM TblEmployee E, TblDepartment D
WHERE E.DeptNo=D.DeptNo;

Copyright © 2016 Pearson Education, Inc. 6-13


EQUI-JOIN EXAMPLE – ALTERNATIVE
SYNTAX “INNER” not
needed

• Structure: Discouraged
• FROM Table1 JOIN Table2 ON (need ( )
Table1.PK = Table2.FK when N >=3)
• Compare last slide:
• FROM Table1, Table2 Recommend
WHERE Table1.PK = Table2.FK ed
Copyright © 2016 Pearson Education, Inc. 6-14
EQUI-JOIN EXAMPLE – ALTERNATIVE
SYNTAX
SELECT E.EmpNo, E.EName, E.DeptNo,
D.DeptNo, D.Loc
FROM TblEmployee E INNER JOIN
TblDepartment D ON E.DeptNo=D.DeptNo;

Copyright © 2016 Pearson Education, Inc. 6-15


Use of
JOIN (THREE METHODS) “_T”:
Note…
 SELECT CUSTOMER_T.CUSTOMER_ID,
ORDER_T.CUSTOMER_ID, CUSTOMER_NAME,Allow
ORDER_ID different
FROM CUSTOMER_T, ORDER_T names for
WHERE CUSTOMER_T.CUSTOMER_ID = PK and FK
ORDER_T.CUSTOMER_ID;
 SELECT CUSTOMER_T.CUSTOMER_ID, ORDER_T.CUSTOMER_ID,
CUSTOMER_NAME, ORDER_ID FROM CUSTOMER_T, ORDER_T
FROM CUSTOMER_T INNER JOIN ORDER_T ON
CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;
 SELECT CUSTOMER_T.CUSTOMER_ID,
ORDER_T.CUSTOMER_ID, CUSTOMER_NAME,
Must use sameORDER_T
ORDER_ID FROM CUSTOMER_T, name for PK &
FK
FROM CUSTOMER_T INNER JOIN
Methods 2 and 3 needs ( ) when # tables ORDER_T USING
>= 3; not
Copyright © 2016 Pearson Education, Inc. 6-16
CUSTOMER_ID; recommended
All records from
OUTER JOIN EXAMPLE table A, PLUS
matching records
from table B
 List the customer name, ID number, and order number
for all customers. Include customer information even
for customers that do have an order.

LEFT OUTER JOIN clause Unlike INNER join, this


causes customer data to will include customer
appear even if there is no rows with no
corresponding order data matching order rows

Why Customer data? Why©not


Copyright OrderEducation,
2016 Pearson data? Inc.
(--Fig 6-2) 6-17
18

Results
EVERY
row in
CUST Unlike
table INNER
[even w/o join, this
will
order], include
PLUS customer
Those rows with
matching no
rows in matching
order
ORDER rows

Refer
Copyright © 2016 back
Pearson to Fig
Education, Inc. 6-2 for
Figure 6-2
Visualization of different join types with results returned
in shaded area

Right Outer Join

The word “OUTER” can be omitted: LEFT JOIN,


RIGHT JOIN
Copyright © 2016 Pearson Education, Inc. 6-19
FIGURE 6-2 (PORTION) - LEFT OUTER JOIN:
WATCH FOR THE SEQUENCE OF TABLE

Do NOT
use outer
join except
when the
biz
scenario Customer_T Order_T
calls for it
CUSTOMER_T is the outer table – ”all records returned
from it” even there is no matching: those who did not
place an order …
Had we reversed the order the tables were listed, …  
Copyright © 2016 Pearson Education, Inc. 6-20
FIGURE “6-2” (EXTENDED) - RIGHT OUTER JOIN:
WATCH FOR THE SEQUENCE OF TABLE
Logically,
A LEFT join B
=
B RIGHT join
A:
All rows in A,
plus matching
rows in B

Order_T RIGHT OUTER JOIN Customer_T

Only need to know


Also see P. 255-257 how to handle LEFT
join; don’t worry
Copyright © 2016 Pearson Education, Inc. 6-21
about RIGHT join
Don’t abuse outer
DISCUSSION: OUTER JOIN (1) join: discussion 7

 When we need, from one of the TWO tables (say


table A), the rows IN ADDITION TO those matching
rows with another table (table B), then OUTER JOIN
should be used

A LEFT JOIN B

A has ALL rows listed,


in addition to those matched

 Put A on left, and A LEFTA LEFT


JOIN JOIN ….
B
Copyright © 2016 Pearson Education, Inc. 6-22
Don’t worry about
RIGHT join; LEFT
DISCUSSION: OUTER JOIN (2) join is sufficient
 When we need, from one of the TWO tables (say
table A), the rows IN ADDITION TO those matching
rows with another table (table B), then OUTER JOIN
should be used
 B RIGHT JOIN A
 A has ALL rows listed,
in addition to those matched

 B…ARIGHT
Put A on right, and RIGHT JOIN JOIN
Copyright © 2016 Pearson Education, Inc. A 6-23
Don’t abuse outer
DISCUSSION: OUTER JOIN (3) join: discussion 7

 Same logic can be achieved using LEFT or RIGHT


joins: Say we want to display ALL records in A, and
those records in B that match with A. Can do either
one:
 SELECT… FROM
 A LEFT JOIN B
 (put A on left, A LEFT JOIN)
 Or:
 SELECT … FROM
 B RIGHT JOIN A
 (put A on right, Right Join A)
The above two codes have the same
Copyright © 2016 Pearson Education, Inc. 6-24
output
Don’t abuse outer
DISCUSSION: OUTER JOIN (4) join: discussion 7

 When we need, from Franchisees table, all the rows


(franchisees) including those who do not own a
restaurant (do not match with Restaurant table)
 Franchisees Fran LEFT JOIN Restaurants
 Franchisees has ALL rows listed,
in addition to those matched

 Put Fr on left, and Fr LEFT JOIN


Fran LEFT JOIN
Rest
Copyright © 2016 Pearson Education, Inc. 6-25
Don’t abuse outer
DISCUSSION: OUTER JOIN (5) join: discussion 7
 When we need, from Franchisees table, all the rows
(franchisees) including those who do not own a
restaurant (do not match with Restaurant table)
 Rest RIGHT JOIN Fran
 Fran has ALL rows listed,
in addition to those matched

 Put Fran on right, and RIGHT JOIN Fran


Rest RIGHT JOIN
Fran
Copyright © 2016 Pearson Education, Inc. 6-26
DISCUSSION (6*): “EQUIVALENCE” OF OUTER JOINS
 A LEFT JOIN B produces the same result as
 B RIGHT JOIN A
  ALL rows in A (including unmatched rows) are
displayed, while B only has matched rows displayed

 Similarly: Mirror
 B LEFT JOIN A produces the same result as
 A RIGHT JOIN B
  ALL rows in B (including unmatched rows) are
displayed, while A only has matched rows displayed
Copyright © 2016 Pearson Education, Inc. 6-27
DISCUSSION (*7*): “GOLDEN RULES” OF OUTER JOIN
 Rule 1:
 OUTER JOIN can only join 2
tables ! !
 *IF*attempt to joinofmore
5-10% than
students twothis
made tables in
outer join, unexpectedmistake
outcomes would
result.
 Rule 2:
 Do NOT abuse outer join: UNLESS you
truly want ALL rows ~15-20% from one table
of students made this
(including unmatched rows),mistake
Copyright © 2016 Pearson Education, Inc.
do NOT 6-28
DISCUSSION (*7.2*): “GOLDEN RULES” OF OUTER
JOIN
 NEVER use OUTER JOIN
 …Unless you are told/hinted to do so.
 OUTER JOIN is not a natural thing you
should think first:
 Ithas VERY specific application scenario,
 which is:
 Among the two tables involved, only when
you want… (complete the sentence)
 Unless the intention in the above bullet is
stated, NEVER use OUTER JOIN
Abuse of outer join is very absurd: “out of
Copyright © 2016 Pearson Education, Inc. 6-29
NOT (!!)
outer
MULTIPLE TABLE JOIN EXAMPLE join!
 Assemble all information necessary to create an invoice for
order number 1006

Four tables
involved in
this join

Each pair of tables requires an equality-check condition in the WHERE clause,


matching primary keys against foreign keys.
Copyright © 2016 Pearson Education, Inc. 6-30
MULTIPLE TABLE JOIN EXAMPLE
NOT (!!)
outer
Join join!
condi
-
tions
from
last
slide N tables,
N-1 join conditions

“Middle” table
must be joined,
even no filed listed
Copyright © 2016 Pearson Education, Inc. 6-31
MULTIPLE TABLE JOIN - *NOTE 1*
 “Bridge” table(s) must be joined, even there are no fields
from these tables are selected to display.
NOT (!!)
 SELECT A.field1, B.field2, B.field3, D.field1 outer
 FROM A, B, C, D join!
 WHERE…

A B C D

Need “Bridge”: No field in C to


display, but table C is needed for
joining
Slide
6-3
Copyright © 2016 Pearson Education, Inc. 6-32
MULTIPLE TABLE JOIN - *NOTE 2*
 Preferred syntax: Assuming joining tables T1, T2,
T3; NOT (!!)
 SELECT… FROM T1, T2, T3 outer
 WHERE T1.pk = T2.fk join!
 AND T2.pk = T3.fk

 If use “JOIN … ON…” then there need to be


parentheses that might not be handled correctly:
 SELECT… FROM ((( ) )
 (T1 JOIN T2 ON T1.pk=T2.fk)
 JOIN T3 ON T2.pk=T3.fk )
 -- if there are 4 tables or more then more levels of
() are neededCopyright © 2016 Pearson Education, Inc. 6-33
N-TABLE JOIN - *NOTE 3*
 CUSTOMER C, ORDER O, PRODUCT P,
ORDERLINE OL

 SELECT CustName, Standard_Price


 FROM C, O, OL, P
 WHERE
 C.Cust_ID=O.Cust_ID
 AND
 O.Order_ID=OL.Order_ID
 AND
need O and OL to “bridge” C and P, even no fields from
 OL.Product_ID=P.Product_ID
We
O or OL
Copyright © 2016 Pearson Education, Inc. 6-34
N-TABLE JOIN - *NOTE 3*

SELECT E.Ename, D.DeptNo, S.Grade,


E.Salary
FROM TblEmployee E, TblDepartment D,
TblSalaryGrade S
WHERE D.DeptNo = E.DeptNo
AND E.Grade = S.Grade
AND E.EName = „BLAKE‟;

Copyright © 2016 Pearson Education, Inc. 6-35


N-TABLE JOIN - *NOTE 4*: COMPLEX METHOD
 CUSTOMER C, ORDER O, PRODUCT P,
ORDERLINE OL

 SELECT CustName, Standard_Price


 FROM ((CUSTOMER C JOIN [ORDER] O
 ON C.Cust_ID=O.Cust_ID)
 JOIN ORDERLINE OL
 ON O.Order_ID=OL.Order_ID)
 JOIN PRODUCT P
 On OL.Product_ID=P.Product_ID
COMPLEX, needs parentheses;
so avoid using this method (“JOIN… ON…”)
Copyright © 2016 Pearson Education, Inc. 6-36
Figure 6-4 Results from a four-table join (edited for readability)
From CUSTOMER_T table

From From PRODUCT_T table


From
ORDER_T ORDERLINE_T
table table
Derived from ORDER_T and PRODUCT_T table:
OrderQuantity * ProductStandartdPrice
Copyright © 2016 Pearson Education, Inc. 6-37
N-TABLE JOIN - *NOTE 3*

SELECT E.Ename, D.DeptNo, S.Grade,


E.Salary
FROM (TblEmployee E JOIN TblDepartment D
ON D.DeptNo = E.DeptNo ) JOIN
TblSalaryGrade S ON E.Grade = S.Grade
WHERE E.EName = „BLAKE‟;

Copyright © 2016 Pearson Education, Inc. 6-38


Unary in ERD; recursive FK in relational
model
SELF-JOIN EXAMPLE

The same table


is used on both
sides of the join
Note which one is which one! (remember
unary? – and
think about
ERDs);
distinguished
using table
aliases

Self-joins are usually used on tables with unary relationships.


Here the Employee table is viewed as E and M, …
Copyright © 2016 Pearson Education, Inc. 6-39
Figure 6-5 Example of a self-join

Employe’s
supervisorID is From Chapter 2

Supervisor’s
EmployID
Unary
1:N

Copyright © 2016 Pearson Education, Inc. 6-40


FIG 6-5 EXAMPLE OF A SELF-JOIN
One table,
treated as
two

Copyright © 2016 Pearson Education, Inc. 6-41


41
SELF-JOIN EXAMPLE - INTERPRETED
 SELECT employee-ID, employee-name of employee
table, employee-name of manager table
 FROM employee_table alias E (for employees),
employee_tbale alias M (for managers)
 WHERE emp_table‟s supervrID = manager_table‟s
empID

Copyright © 2016 Pearson Education, Inc. 6-42


A “VISUAL AID” FOR SELF JOIN
Employee’s Employee’s
EmployeeID SupervisorID
= =
Supervisor’s Supervisor’s
SupervisorID SupervisorID

Employee’s Employee’s
EmployeeID SupervisorID
= =
Supervisor’s Supervisor’s
EmployeeID EmployeeID
Copyright © 2016 Pearson Education, Inc. 6-43
SELF-JOIN EXAMPLE

SELECT Worker.EName AS Name, E.EName


AS Manager
FROM TblEmployee Worker, TblEmployee E
WHERE Worker.Mgr = E.EName;

Copyright © 2016 Pearson Education, Inc. 6-44


JOIN VS. SUBQUERY
 Some queries could be accomplished by either a
join or a subquery

Join version

Subquery version

Copyright © 2016 Pearson Education, Inc. 6-52


Figure 6-6 Graphical depiction of two ways to
answer a query with different types of joins

Copyright © 2016 Pearson Education, Inc. 6-53


Figure 6-6 Graphical depiction of two ways to
answer a query with different types of joins

Copyright © 2016 Pearson Education, Inc. 6-54


 SELECT ename, deptno FROM Employee
WHERE deptno = (SELECT deptno FROM
Department WHERE dname = „SALES‟)
 SELECT ename, D.deptno, dname FROM
Employee E, Department D WHERE
E.deptno = D.deptno AND dname = „SALES‟
 SELECT ename, D.deptno, dname FROM
Employee E JOIN Department D ON
E.deptno = D.deptno WHERE dname =
„SALES‟ Copyright © 2016 Pearson Education, Inc. 6-55

Das könnte Ihnen auch gefallen