Displaying Data From Multiple Tables
Displaying Data From Multiple Tables
Objectives
Write SELECT statements to access data from more than one table using equality and nonequality joins View data that generally does not meet a join condition by using outer joins Join a table to itself
ORDER_T
CUSTOMER_NAM E Contemporary Casuals Value Furniture POSTAL_ CODE 32601 75094
ORDER_ID
ORDER_DATE
CUSTOMER_ID
CUSTOMER_NAME
POSTAL_CODE
1001
1002 1010
21-OCT-00
21-OCT-00
1
8
Contemporary Casuals
California Classics
32601
96915
05-NOV-00
Contemporary Casuals
32601
What Is a Join?
Write the join condition in the WHERE clause. Prefix the column name with the table name when the same column name appears in more than one table.
Cartesian Product
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 in a WHERE clause.
Types of Joins
Equijoin Non-Equijoin Outer-join Self-join
What Is an Equijoin?
EMP
EMPNO ENAME DEPTNO ------ ------- ------7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20 ... 14 rows selected.
DEPT
DEPTNO ------10 30 10 20 30 30 30 30 30 20 20 ... 14 rows DNAME ---------ACCOUNTING SALES ACCOUNTING RESEARCH SALES SALES SALES SALES SALES RESEARCH RESEARCH selected. LOC -------NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO DALLAS DALLAS
Primary key
Foreign key
Use table prefixes to qualify column names that are in multiple tables. Improve performance by using table prefixes. Distinguish columns that have identical names but reside in different tables by using column aliases.
SELECT
FROM WHERE
Non-Equijoins
SELECT product_description, standard_price, grade FROM product_t, grade_t WHERE standard_price BETWEEN low AND high
Outer Joins
You use an outer join to also see rows that do not usually meet the join condition.
SELECT table.column, table.column FROM table1 LEFT/RIGHT JOIN table2 ON (table1.column = table2.column);
SELECT o.order_id, c.customer_name FROM order_t o RIGHT JOIN customer_t c ON (o.customer_id = c.customer_id);
Self Joins
EMP (WORKER)
EMPNO ----7839 7698 7782 7566 7654 7499 ENAME -----KING BLAKE CLARK JONES MARTIN ALLEN MGR ---7839 7839 7839 7698 7698
EMP (MANAGER)
EMPNO ENAME ----- -------7839 7839 7839 7698 7698 KING KING KING BLAKE BLAKE
WORKER.ENAME||'WORKSFOR'||MANAG ------------------------------BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE ... 13 rows selected.
Summary
SELECT FROM WHERE table1.column, table2.column table1, table2 table1.column1 = table2.column2;
Equijoin
Non-Equijoin
Outer-join
Self-join