• No results found

Joining Tables in Queries

N/A
N/A
Protected

Academic year: 2021

Share "Joining Tables in Queries"

Copied!
30
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

2

Objectives

You will be able to

 Write SQL queries that use Join operations to

(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.

(4)

The Northwinds Database (Subset) Customers CustomerID CompanyName ContactName ContactTitle Address City Region PostalCode Country Phone Fax Order Details OrderID ProductID UnitPrice Quantity Discount Orders OrderID CustomerID EmployeeID OrderDate RequiredDate ShippedDate ShipVia Freight ShipName ShipAddress ShipCity ShipRegion ShipPostalCode ShipCountry Products ProductID ProductName SupplierID CategoryID QuantityPerUnit UnitPrice UnitsInStock UnitsOnOrder ReorderLevel Discontinued Suppliers SupplierID 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

(6)

6

Types of Joins

 SQL defines several types of joins.  The simplest is the inner join.

 It has the form:

SELECT TABLE1.COLUMN1, TABLE2.COLUMN2 FROM TABLE1, TABLE2

WHERE 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

(8)

8

Inner Join Example

 Objective:

 Determine the name of the

(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)

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:

(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)

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)

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

(15)
(16)

Joining More than Two Tables 1> 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)

18

(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.

(20)
(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)

22

(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.

(24)

24

Class Product

public 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);

(26)
(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)

28

(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)

30

App in Action

References

Related documents

This study aimed to gather the perspectives of transgender/non-binary individuals on four issues: overall perception of genetic counseling; language and terminology used in genetic

The analysis of the stabilization period of the micromorph PV module is carried out by following the same steps presented above. The evolution of the filtered DC output power of

While most products analyzed scored in the upper range for ‘material recovery potential’, the ‘likely material recovery ’ could provide a more accurate

*The remainder of this cover page shall be filled out for a reporting person’s initial filing on this form with respect to the subject class of securities, and for any

In Swedish plant-level data for manufacturing 1970–96 relatively less employ- ment is in low-productivity plants after decentralisation than before, but the correlation between

Proportion of diabetes type 2 (T2DM) care trajectory (CT) patients with > = 3 HbA1c measures around CT start, in comparison with T2DM patients on a diabetes convention 3A

DESCRIPTION NAME NOTICE NAME ADDRESS 1 ADDRESS 2 CITY E CODE COUNTRY PHONE FAX EMAIL. COUNSEL TO PAOLI SHOPPING

If foreign equity in the country and rentability of foreign owned companies affect GDP more than rentability of domestic companies, foreign ownership is more efficient for the