Joining Tables in Queries



Similar documents
In-Depth Guide Advanced Database Concepts

Oracle Application Express - Application Migration Workshop

SQL SELECT Query: Intermediate

QWT Business Intelligence Project Plan

Database Query 1: SQL Basics

Module 9: Implementing Stored Procedures

Database Linker Tutorial

Using AND in a Query: Step 1: Open Query Design

Business Intelligence. 11. SSIS, ETL January 2014.

Session E-SQL Solving Common Problems with Visual FoxPro's SQL

BPMN-Based Conceptual Modeling of ETL Processes

Implementing a WCF Service in the Real World

Access Queries (Office 2003)

Essentials of SQL. Essential SQL 11/06/2010. NWeHealth, The University of Manchester

In Memory Database. Performance evaluation based on query time. Seminar Database Systems

Module 5: Joining Multiple Tables

Advanced Transact-SQL for SQL Server 2000 Practical T-SQL solutions (with code) to common problems

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

VBScript Database Tutorial Part 1

Working with Data in ASP.NET 2.0 :: Creating Stored Procedures and User Defined Functions with Managed Code Introduction

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.


Business Reports with L A TEX

DESIGNING A LOGICAL DATA MODEL FOR A SALES AND INVENTORY MANAGEMENT SYSTEM

Talking to Databases: SQL for Designers

How to use MySQL Workbench and other development tools

Information Systems SQL. Nikolaj Popov

2. Which three statements about functions are true? (Choose three.) Mark for Review (1) Points

SQL 2: GETTING INFORMATION INTO A DATABASE. MIS2502 Data Analytics

Ken Goldberg Database Lab Notes. There are three types of relationships: One-to-One (1:1) One-to-Many (1:N) Many-to-Many (M:N).

Relational Database: Additional Operations on Relations; SQL

Lab # 5. Retreiving Data from Multiple Tables. Eng. Alaa O Shama

1 Structured Query Language: Again. 2 Joining Tables

Paper HW-03. Planning for and Designing a Data Warehouse: A Hands on Workshop. Gregory S. Nelson ThotWave Technologies, Cary, North Carolina

Microsoft Access XP Beginners: Exercises

Paging, sorting, and searching using EF Code first and MVC 3. Introduction. Installing AdventureWorksLT database. Creating the MVC 3 web application

Topic: Relationships in ER Diagram and Relationships in MS Access

CHAPTER 12. SQL Joins. Exam Objectives

Using Microsoft Excel for Data Presentation Peter Godard and Cyndi Williamson, SRI International, Menlo Park, CA

Using PROC SQL and PROC TRANSPOSE to provide Excel s Pivot functions Mai Nguyen, Shane Trahan, Inga Allred, Nick Kinsey

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

RDBMS Using Oracle. Lecture Week 7 Introduction to Oracle 9i SQL Last Lecture. kamran.munir@gmail.com. Joining Tables

Database Development and Management with SQL

Advantage Database Server

Go Beyond VFP's SQL with SQL Server

Title. Syntax. stata.com. odbc Load, write, or view data from ODBC sources. List ODBC sources to which Stata can connect odbc list

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

AXUS EMPLOYEE RECRUITMENT SYSTEM SHADIRA BINTI SAAD

MICROSOFT ACCESS 2003 TUTORIAL

Tutorial on Relational Database Design

Modeling Guide for SAP Web IDE for SAP HANA

CS251: Fundamentals of Database Systems 1. CS251: Fundamentals of Database Systems. Database Design Project. Trina VanderLouw

OpenReports: Users Guide

REPORT DESIGN GUIDE. Version 6.5

Where? Originating Table Employees Departments

Query Builder. The New JMP 12 Tool for Getting Your SQL Data Into JMP WHITE PAPER. By Eric Hill, Software Developer, JMP

Online shopping store

Visual COBOL ASP.NET Shopping Cart Demonstration

The join operation allows you to combine related rows of data found in two tables into a single result set.

RECURSIVE COMMON TABLE EXPRESSIONS DATABASE IN ORACLE. Iggy Fernandez, Database Specialists INTRODUCTION

Fundamentals of Database System

Querying Microsoft SQL Server 2000 with Transact-SQL Delivery Guide. Course Number: 2071A

SQL Programming. Student Workbook

Introduction to SQL for Data Scientists

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Displaying Data from Multiple Tables

Bubble Code Review for Magento

Global Transport Secure ecommerce. Web Service Implementation Guide

Virtuoso Replication and Synchronization Services

Displaying Data from Multiple Tables. Copyright 2006, Oracle. All rights reserved.

Full Text Search. Objectives. Full Text Search

Conceptual Design: Entity Relationship Models. Objectives. Overview

Joins and subqueries: Using SQL commands for the hard stuff

T-SQL STANDARD ELEMENTS

Oracle SQL. Course Summary. Duration. Objectives

P_Id LastName FirstName Address City 1 Kumari Mounitha VPura Bangalore 2 Kumar Pranav Yelhanka Bangalore 3 Gubbi Sharan Hebbal Tumkur

Making OData requests from jquery and/or the Lianja HTML5 Client in a Web App is extremely straightforward and simple.

Displaying Data from Multiple Tables. Copyright 2004, Oracle. All rights reserved.

SQL. Basics of Structured Query Language (ISO/CEI 9075:2011) focused mainly on Oracle 11g r2 for undergraduates (end-users)

Merging Data with Joins and Unions

Displaying Data from Multiple Tables. Copyright 2004, Oracle. All rights reserved.

Why Zalando trusts in PostgreSQL

In this Lecture SQL SELECT. Example Tables. SQL SELECT Overview. WHERE Clauses. DISTINCT and ALL SQL SELECT. For more information

Access 2010: Creating Queries Table of Contents INTRODUCTION TO QUERIES... 2 QUERY JOINS... 2 INNER JOINS... 3 OUTER JOINS...

GoGetSSL API Guide Version: 2.5 (stable)

Quick Start SAP Sybase IQ 16.0

Furthermore remember to uninstall the old DWI client before replacing it with the new version.

Developing Web Applications for Microsoft SQL Server Databases - What you need to know

Apache Tuscany RDB DAS

Microsoft Access Lesson 5: Structured Query Language (SQL)

Introduction to Microsoft Jet SQL

!"#"$%&'(()!!!"#$%&'())*"&+%

Relational Division and SQL

Transcription:

Joining Tables in Queries 1

Objectives You will be able to Write SQL queries that use Join operations to retrieve information from multiple tables. 2

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

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

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

Types of Joins SQL defines several types of joins. The simplest is the inner join. It has the form: Whatever you want from either table SELECT TABLE1.COLUMN1, TABLE2.COLUMN2 FROM TABLE1, TABLE2 WHERE TABLE1.COLUMN_X = TABLE2.COLUMN_Y Query will return selected items from every pair of rows for which this condition is true. 6

Inner Join Example Running sqlcmd with the Northwind Database 7

Inner Join Example Objective: Determine the name of the customer's contact on all orders. 8

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> 9

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 10

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> 11

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

Table Aliases 1> SELECT O.ORDERID, C.CONTACTNAME 2> FROM ORDERS O, CUSTOMERS C Table Aliases 3> WHERE C.CUSTOMERID = O.CUSTOMERID 4> AND O.ORDERID = 10261 5> GO ORDERID CONTACTNAME ----------- ------------------------------ 10261 Bernardo Batista (1 rows affected) 1> 13

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 14

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>

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

The Northwinds Product Browser 18

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

Products and Suppliers

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

Check Command in SQLCMD 22

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

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; } } 24

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

Class Product_Information

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

Product Browser in Action 28

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" ; 29

App in Action End of Presentation 30