25
Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Embed Size (px)

Citation preview

Page 1: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views

CS 320

Page 2: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Review: Inner Join Queries

Retrieve records from multiple tables Tables must have links through primary

key/foreign key relationships

Page 3: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Problem: What if you want to create a query that retrieves records

from two tables even if all of the records don't have matching records in a joined table?

Example: Create a query that retrieves the customer ID and name of every customer, along with the purchase dates of all of the customer’s purchases. Do not retrieve duplicate records, and order the values by customer ID. Problem: some customers have not made

purchases!

SELECT DISTINCT cust.cust_id, cust_name, purch_dateFROM candy_customer cust JOIN candy_purchase purchON cust.cust_id = purch.cust_idORDER BY cust.cust_id;

Page 4: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Solution: Create an Outer Join Retrieves all of the records from one table, and

also retrieves the matching columns from a second table Retrieves the records in the first table even if they

don’t have matching records in the second table Types of outer joins:

Left Right Full (not supported by MySQL)

Page 5: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Left Outer Join Retrieves all of the records in the left (first)

table, along with matching records in the right (second) table, if they exist

General syntax:

SELECT field1, field2, …FROM Table1 LEFT OUTER JOIN Table2ON join_conditionWHERE search_condition(s);

NOTE: the word "OUTER" is optional

Page 6: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Left Outer Join Example

SELECT DISTINCT c.cust_id, cust_name, purch_dateFROM candy_customer c LEFT JOIN candy_purchase pON c.cust_id = p.cust_idORDER BY c.cust_id

Page 7: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Right Outer Join Retrieves all of the records in the right

(second) table, along with matching records in the left (first) table, if they exist

General syntax:

SELECT field1, field2, …FROM table_1 RIGHT JOIN table_2ON join_conditionWHERE search_condition(s);

Page 8: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Self Joins Join the table to itself

using a table alias

ACME_EMPLOYEEEmployee_IDEmployee_First_NameEmployee_Last_NameEmployee_DOBSupervisorID (FK)

SELECT emp.employee_last_name AS employee, sup.employee_last_name AS supervisorFROM acme_employee emp JOIN acme_employee supON emp.supervisor_id = sup.employee_id;

Employee_ID

Employee_First_Name

Employe_Last_Name

Employee_DOB

Supervisor_ID

1 Mary Smith 7/14/1968

2 John Jones 2/19/1972 1

3 Jason Swift 11/28/1975 1

Page 9: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Self JoinsEmployee_ID

Employee_First_Name

Employe_Last_Name

Employee_DOB

Supervisor_ID

1 Mary Smith 7/14/1968

2 John Jones 2/19/1972 1

3 Jason Swift 11/28/1975 1

EMP alias

Employee_ID

Employee_First_Name

Employe_Last_Name

Employee_DOB

Supervisor_ID

1 Mary Smith 7/14/1968

2 John Jones 2/19/1972 1

3 Jason Swift 11/28/1975 1

SUP alias

SELECT emp.employee_last_name AS employee, sup.employee_last_name AS supervisorFROM acme_employee emp JOIN acme_employee supON emp.supervisor_id = sup.employee_id;

Page 10: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Consist of a main query and a subquery Subquery retrieves a search condition value

for the main query

Uses Alternative way to retrieve data from one table

based on a search condition from another table Sometimes it's the only way you can retrieve the

data you need

Nested Queries

Page 11: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Nested Query Syntax

SELECT purch_id, purch_date, purch_poundsFROM candy_purchaseWHERE prod_id =(SELECT prod_idFROM candy_productWHERE prod_desc = 'Celestial Cashew Crunch')

Page 12: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

The subquery returns exactly ONE value The SearchColumn in the main query MUST

MATCH the SearchColumn in the subquery The SearchColumn is usually a foreign key

value

Nested Query Example NotesSELECT purch_id, purch_date, purch_poundsFROM candy_purchaseWHERE prod_id =(SELECT prod_idFROM candy_productWHERE prod_desc = 'Celestial Cashew Crunch')

Page 13: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Use if the subquery might retrieve multiple values

Alternate Nested Query Syntax

SELECT cust_id, purch_id, purch_date, purch_poundsFROM candy_purchaseWHERE cust_id IN(SELECT cust_idFROM candy_customerWHERE cust_type = 'P')

Page 14: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

The main query in a nested query can have multiple search conditions whose values are specified by separate subqueries:

Nested Queries with Multiple Subqueries

SELECT purch_id, purch_dateFROM candy_purchaseWHERE prod_id = (SELECT prod_id FROM candy_product WHERE prod_desc = 'Celestial Cashew Crunch')AND cust_id IN (SELECT cust_id FROM candy_customer WHERE cust_type = 'P')

Page 15: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

SELECT prod_descFROM candy_productWHERE prod_id IN (SELECT prod_id FROM candy_purchase WHERE purch_date = '2004-10-29' AND cust_id IN (SELECT cust_id FROM candy_customer WHERE cust_type = 'P'))

A subquery can also be a nested query:

Note positions of the nesting parentheses

Nested Subqueries

Page 16: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

For many nested queries, you could achieve the same result with a join queryNested may seem more straight-forward than the

equivalent join queryDownside:

Executes more slowly Final result can only come from the main query table

Some nested query results can’t be retrieved through a join

Notes on Using Nested Queries

Page 17: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Query requiring a nested query: Create a query that retrieves the IDs of all customers

whose average purchase amount is greater than the average pounds of all customers' purchases

SELECT cust_id, AVG(purch_pounds)FROM candy_purchaseGROUP BY cust_idHAVING AVG(purch_pounds) > (SELECT AVG(purch_pounds) FROM candy_purchase);

Page 18: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Create and debug the subquery(ies) first, then add the main query

If the main query doesn’t run, debug it by hard-coding the search condition rather than using the subquery

Strategy for Creating and Debugging Nested Queries

Page 19: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Views

Virtual table based on a query You can think of it as a stored query

Purposes:Controls the fields that certain users can

accessProvides a way to simplify join queries

Page 20: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Types of Views

Simple view: based on a single table

Primary use: hides fields to control accessUsers can select, insert, update, and delete

from simple views just as with tables

CREATE OR REPLACE VIEW candy_customer_view ASSELECT cust_id, cust_name, cust_type, cust_addr,cust_zipFROM candy_customer;

Page 21: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Types of Views Complex view: created by joining multiple tables

Primary use: to simplify queries Users can select from complex views Users CANNOT insert, update, and delete from

complex views

CREATE OR REPLACE VIEW purchases_view ASSELECT cust_name, purch_date, purch_delivery_date, prod_desc, purch_pounds FROM candy_purchase purch INNER JOIN candy_product prodON purch.prod_id = prod.prod_idJOIN candy_customer cust ON cust.cust_id = purch.cust_id;

Page 22: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Test Yourself: You need to retrieve the description of all candy products, along with the purchase date and pounds purchased. You need to create a(n) _________ query.

a. Inner join

b. Outer join

c. Nested

d. View

e. None of the above

Page 23: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Test Yourself: You need to retrieve the description of all candy products, along with the purchase date and pounds purchased. You need to create a(n) _________ query.

a. Inner join

b. Outer join

c. Nested

d. View

e. None of the above

Page 24: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Test Yourself: How many records does the following query retrieve?

a. 9

b. 14

c. 7

d. None of the above

SELECT DISTINCT c.cust_id, cust_name, purch_dateFROM candy_customer c RIGHT JOIN candy_purchase pON c.cust_id = p.cust_idORDER BY c.cust_id

Page 25: Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Test Yourself: How many records does the following query retrieve?

a. 9

b. 14

c. 7

d. None of the above

SELECT DISTINCT c.cust_id, cust_name, purch_dateFROM candy_customer c RIGHT JOIN candy_purchase pON c.cust_id = p.cust_idORDER BY c.cust_id