Download presentation
Presentation is loading. Please wait.
Published byGunner Segroves Modified over 10 years ago
1
SQL – Part 2 Multiple Tables CIS 324 – Chapter 5
2
Sub-Queries Example – We need the names of all employees (not their employee number) for all employees who worked more than 40 hours on an assignment. Sub-Queries – Nested Queries (Effective when the results ultimately comes from ONE table) SELECTName FROMEMPLOYEE WHEREEmployeeNumber IN (SELECTDISTINCT EmployeeNum FROMASSIGNMENT WHEREHoursWorked > 40);
3
Sub Queries (cont) Multiple nesting is allowed: What if we only need Accounting projects from the above example: SELECTName FROMEMPLOYEE WHEREEmployeeNumber IN (SELECTDISTINCT EmployeeNum FROMASSIGNMENT WHEREProjectID IN ( SELECTProjectID FROMPROJECT WHEREDepartment = Accounting));
4
Joins When we need to display data from 2 or more tables SELECTName, HoursWorked FROMEMPLOYEE, ASSIGNMENT WHEREEmployeeNumber = EmployeNum; This creates a new table with Name from the EMPLOYEE table and HoursWorked from the ASSIGNMENT table when the condition of matching employee numbers occurs. A join is just another table so all earlier SQL statements are available for use. (Group BY, WHERE, etc.)
5
Multiple Table Joins We can join more than 2 tables together: SELECTProject.Name, HoursWorked, EMPLOYEE.Name FROMPROJECT, ASSIGNMENT, EMPLOYEE WHEREPROJECT.ProjectID = ASSIGNMENT.ProjectID ANDEMPLOYEE.EmployeeNumber = ASSIGNMENT.EmployeeNum;
6
Joins (cont) If two columns in separate tables have the same column name you will need to indicate the table name and column name in the WHERE statement: SELECT Name, HoursWorked FROMPROJECT, ASSIGNMENT WHEREPROJECT.ProjectID = ASSIGNMENT.ProjectID; If not all rows in both tables have a match in the join condition – these rows will not appear in the join table.
7
Outer Joins OUTER JOIN – Not part of SQL Standard but supported by most DBMS – Solution to dropping data in standard join An outer join appends the rows in the select statement onto the existing table on either the left or right side: SELECTName, HoursWorked FROMPROJECT LEFT JOIN ASSIGNMENT WHEREPROJECT.ProjectID = ASSIGNMENT.ProjectID;
8
Sample Outer Join This appends the name of the project to the left side of the assignment table. The unmatched rows will receive a null value: Q3 Portfolio Analysis17.50 Q3 Portfolio Analysis12.50 Q3 Portfolio Analysis8.00 Q3 Portfolio Analysis20.25 Q3 Tax Prep45.75 Q3 Tax Prep70.50 Q3 Tax Prep40.50 Q4 Product Plan75.00 Q4 Product Plan20.25 Q4 Product Plan25.25 Q4 Portfolio Analysisnull
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.