1 joining tables in queries. 2 objectives you will be able to write sql queries that use join...

30
1 Joining Tables in Queries

Upload: mae-cameron-lynch

Post on 31-Dec-2015

218 views

Category:

Documents


0 download

TRANSCRIPT

1

Joining Tables in Queries

2

Objectives

You will be able to Write SQL queries that use Join

operations to retrieve information from multiple tables.

3

Retrieving from Multiple Tables

We often need to retrieve information from multiple tables in a single query. Example:

Show the name of the customer contact for all orders in the Northwinds database.

The Northwinds Database (Subset)

CustomersCustomerID

CompanyName

ContactName

ContactTitle

Address

City

Region

PostalCode

Country

Phone

Fax

Order DetailsOrderID

ProductID

UnitPrice

Quantity

DiscountOrders

OrderID

CustomerID

EmployeeID

OrderDate

RequiredDate

ShippedDate

ShipVia

Freight

ShipName

ShipAddress

ShipCity

ShipRegion

ShipPostalCode

ShipCountry

ProductsProductID

ProductName

SupplierID

CategoryID

QuantityPerUnit

UnitPrice

UnitsInStock

UnitsOnOrder

ReorderLevel

Discontinued

SuppliersSupplierID

CompanyName

ContactName

ContactTitle

Address

City

Region

PostalCode

Country

Phone

Fax

HomePage

5

Retrieving from Multiple Tables

The Orders table has the Customer ID but not the customer’s contact name.

The Customers table has the contact name.

In order to determine the customer contact for an order, we need to get the Customer ID from the Orders table and then get the contact name for that Customer ID from the Customers table.

The SQL “join” operation makes this possible with a single query.

Retrieve pairs of rows from two tables having identical values of some key.

6

Types of Joins

SQL defines several types of joins.

The simplest is the inner join.

It has the form:

SELECT TABLE1.COLUMN1, TABLE2.COLUMN2FROM TABLE1, TABLE2WHERE TABLE1.COLUMN_X = TABLE2.COLUMN_Y

Whatever you want from either table

Query will return selected items from every pair of rows for which this condition is true.

7

Inner Join Example

Running sqlcmd with the Northwind Database

8

Inner Join Example

Objective: Determine the name of the

customer's contact on all orders.

9

Inner Join Example

1> SELECT ORDERS.ORDERID, CUSTOMERS.CONTACTNAME

2> FROM ORDERS, CUSTOMERS

3> WHERE CUSTOMERS.CUSTOMERID = ORDERS.CUSTOMERID

4> GO

ORDERID CONTACTNAME

----------- ------------------------------

10643 Maria Anders

10692 Maria Anders

10702 Maria Anders

10835 Maria Anders

10952 Maria Anders

11011 Maria Anders

...

10860 Carine Schmitt

10971 Carine Schmitt

(830 rows affected)

1>

10

Being More Selective

We could add more conditions to the WHERE clause.

Suppose we wanted the contact name for just one specific order.

We could add to the query:AND ORDERS.ORDERID=11012

11

Inner Join Example

1> SELECT ORDERS.ORDERID, CUSTOMERS.CONTACTNAME

2> FROM ORDERS, CUSTOMERS

3> WHERE CUSTOMERS.CUSTOMERID = ORDERS.CUSTOMERID

4> AND ORDERS.ORDERID=11012

5> GO

ORDERID CONTACTNAME

----------- ------------------------------

11012 Peter Franken

(1 rows affected)

1>

12

Table Aliases

We can give a table a temporary name within a single SQL statement A short name saves keystokes and

makes the statement easier to read and understand.

Write the (short) temporary name immediately after the real table name in the FROM clause.

13

1> SELECT O.ORDERID, C.CONTACTNAME

2> FROM ORDERS O, CUSTOMERS C

3> WHERE C.CUSTOMERID = O.CUSTOMERID

4> AND O.ORDERID = 10261

5> GO

ORDERID CONTACTNAME

----------- ------------------------------

10261 Bernardo Batista

(1 rows affected)

1>

Table Aliases

Table Aliases

14

Joining More than Two Tables

Any number of tables can be included in a join operation.

Suppose we want to see the name of each product on any order by Customer VINET

VINET is the Customer ID

Joining More than Two Tables1> SELECT P.ProductName

2> FROM Products P, [Order Details] OD, Orders O, Customers C

3> WHERE P.ProductID = OD.ProductID

4> AND OD.OrderID = O.OrderID

5> AND O.CustomerID = C.CustomerID

6> AND C.CustomerID = 'VINET'

7> GO

ProductName

----------------------------------------

Queso Cabrales

Singaporean Hokkien Fried Mee

Mozzarella di Giovanni

Flotemysost

Mozzarella di Giovanni

Gnocchi di nonna Alice

Konbu

Jack's New England Clam Chowder

Inlagd Sill

Filo Mix

(10 rows affected)

1>

17

The Northwind Product Browser

Let’s extend the Northwind Product Browser to show the supplier for each product.

Download the final version of the example done in class:

http://www.cse.usf.edu/~turnerr/Software_Systems_Development/Downloads/2011_04_05_Northwind_Product_Browser/

File Northwind_Product_Browser.zip

Expand zip file. Build and run.

18

The Northwinds Product Browser

19

The Northwind Product Browser

We would like to show the supplier for each product along with the other product information.

We can use a join to get related information along with the product information.

Products and Suppliers

21

Products and Suppliers

The Product table includes a SupplierID. Not meaningful to the user.

The Supplier table includes the supplier's CompanyName which is meaningful.

Tables are related by SupplierID

Use an inner join to get the CompanyName of the supplier of each product from the Supplier table.

22

Check Command in SQLCMD

23

Class Products

Class Products is responsible for the query.

SqlCommand1.CommandText =

"SELECT P.*, S.CompanyName " +

"FROM Products P, Suppliers S " +

"WHERE P.SupplierID = S.SupplierID";

Build and run. Existing code is not affected by the change to the query.

24

Class Productpublic class Product{ private String product_name; private int product_id; private decimal unit_price; private short units_in_stock; private bool discontinued; private String supplier_name;

...

public String Supplier_name

{

get { return supplier_name; }

set { supplier_name = value; }

}

25

Class Product

// This constructor initializes a product

// using a query result.

public Product(SqlDataReader rdr)

{

Product_name = rdr.GetString(1);

Product_id = rdr.GetInt32(0);

Supplier_name = rdr.GetString(10);

Class Product_Information

27

Product_Information.cs

private void Display_Current_Record()

{

Product p = Product_List[current_record_number];

tbProductName.Text = p.Product_name;

tbProductID.Text = p.Product_id.ToString();

tbUnitPrice.Text = p.Unit_price.ToString();

tbUnitsInStock.Text = p.Units_in_stock.ToString();

cbDiscontinued.Checked = p.Discontinued;

tbSupplier.Text = p.Supplier_name;

tbRecordNumber.Text =

"Record " + (current_record_number + 1) +

" of " + Product_List.Count;

Update_Buttons();

}

28

Product Browser in Action

29

List Alphabetically

Let’s show the products in alphabetical order by ProductName.

Revised query:

sc.CommandText = "SELECT P.*, S.CompanyName " +

"FROM Products P, Suppliers S " +

"WHERE P.SupplierID = S.SupplierID " +

"ORDER BY P.ProductName" ;

30

App in Action

End of Presentation