CS 122: Lecture 3 Joins (Part 1) Tarik Booker CS 122 California State University, Los Angeles October 7, 2014.

Slides:



Advertisements
Similar presentations
Database Relationships in Access As you recall, the data in a database is stored in tables. In a relational database like Access, you can have multiple.
Advertisements

© Abdou Illia MIS Spring 2014
Join Queries CS 146. Introduction: Join Queries So far, our SELECT queries have retrieved data from a single table Usually queries combine data from multiple.
Chapter 4 Joining Multiple Tables
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 3: Joins Part I.
A Guide to SQL, Seventh Edition. Objectives Use joins to retrieve data from more than one table Use the IN and EXISTS operators to query multiple tables.
Displaying Data from Multiple Tables
5 Copyright © 2004, Oracle. All rights reserved. Displaying Data from Multiple Tables.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
Introduction to Oracle9i: SQL1 Basic SQL SELECT Statements.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 3: Joins Part I.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 9: Data Manipulation Language.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 5: Subqueries and Set Operations.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 4: Joins Part II.
Using Relational Databases and SQL Department of Computer Science California State University, Los Angeles Lecture 7:
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 4: Joins Part II.
Inner join, self join and Outer join Sen Zhang. Joining data together is one of the most significant strengths of a relational database. A join is a query.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
Introduction to SQL Structured Query Language Martin Egerhill.
Using Relational Databases and SQL Department of Computer Science California State University, Los Angeles Lecture 8: Subqueries.
Learningcomputer.com SQL Server 2008 – Entity Relationships in a Database.
RELATIONSHIPS Generally there are two main database types: flat-file and relational.
Using Relational Databases and SQL John Hurley Department of Computer Science California State University, Los Angeles Lecture 3: Joins Part I.
Lecture 2 of Advanced Databases Advanced SQL Instructor: Mr.Ahmed Al Astal.
Chapter 9 Joining Data from Multiple Tables
A Guide to MySQL 5. 2 Objectives Use joins to retrieve data from more than one table Use the IN and EXISTS operators to query multiple tables Use a subquery.
Banner and the SQL Select Statement: Part Three (Joins) Mark Holliday Department of Mathematics and Computer Science Western Carolina University 4 November.
Using Relational Databases and SQL Department of Computer Science California State University, Los Angeles Lecture 6: Midterm Review.
1 Outline  What is a Primary Key?  AutoNumber primary keys  Single-field primary keys  Composite-field primary key  About Foreign Keys  Database.
JOI/1 Data Manipulation - Joins Objectives –To learn how to join several tables together to produce output Contents –Extending a Select to retrieve data.
® Microsoft Access 2010 Tutorial 9 Using Action Queries and Advanced Table Relationships.
Chapter 4Introduction to Oracle9i: SQL1 Chapter 4 Joining Multiple Tables.
Join, Subqueries and set operators. Obtaining Data from Multiple Tables EMPLOYEES DEPARTMENTS … …
Using Relational Databases and SQL John Hurley Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
Tutorial 9 Using Action Queries and Advanced Table Relationships.
Using Relational Databases and SQL Department of Computer Science California State University, Los Angeles Lecture 4: Joins Part II.
CS424 Relational Data Manipulation Relational Data Manipulation Relational tables are sets. Relational tables are sets. The rows of the tables can be considered.
Database revision.
5 Copyright © 2004, Oracle. All rights reserved. Displaying Data from Multiple Tables.
5 Copyright © 2004, Oracle. All rights reserved. Displaying Data from Multiple Tables.
Displaying Data from Multiple Tables (SQL99 Syntax with examples)
While you are waiting for class to start... (1)Login to SQL Server 2012 Management Studio (2) Execute the file called “SQLLab4.sql”. It is located on the.
* Database is a group of related objects * Objects can be Tables, Forms, Queries or Reports * All data reside in Tables * A Row in a Table is a record.
U:/msu/course/cse/103 Day 08, Slide 1 CSE 103 Students: –Review days 7 and 8 if you need to go over relationships and INNER.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
Join Queries CS 146. Introduction: Join Queries  So far, our SELECT queries have retrieved data from a single table  Usually queries combine data from.
Quiz Which of the following is not a mandatory characteristic of a relation? Rows are not ordered (Not required) Each row is a unique There is a.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
CS122 Using Relational Databases and SQL Huiping Guo Department of Computer Science California State University, Los Angeles 2. Single Table Queries.
Lecture 7: Subqueries Tarik Booker California State University, Los Angeles.
Tarik Booker CS 122. What we will cover… Tables (review) SELECT statement DISTINCT, Calculated Columns FROM Single tables (for now…) WHERE Date clauses,
Advanced SQL Advanced Database Dr. AlaaEddin Almabhouh.
Joins (Part II) Tarik Booker California State University, Los Angeles.
CS122 Using Relational Databases and SQL Huiping Guo Department of Computer Science California State University, Los Angeles 4. Subqueries and joins.
SQL – join.
CS122 Using Relational Databases and SQL
Lyric Database Lyric Music
CS122 Using Relational Databases and SQL
CS122 Using Relational Databases and SQL
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
CS122 Using Relational Databases and SQL
David M. Kroenke and David J
CS122 Using Relational Databases and SQL
Contents Preface I Introduction Lesson Objectives I-2
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
Lyric Database Lyric Music
Presentation transcript:

CS 122: Lecture 3 Joins (Part 1) Tarik Booker CS 122 California State University, Los Angeles October 7, 2014

What we cover…  Keys  Primary (review), Foreign  Combining Tables  Why, How?  Cartesian Product  Joins  Cross Joins  Named Column Joins  Qualified Table Names  Named Column Join  Equi-Join  Table Aliases  Inner Joins  Natural Joins  Joining More than One Table  Solving Join Problems  Join Expressions

Keys!  Primary Keys  What is the definition of a Primary Key?  Primary Key for GET?  Foreign Keys  Primary Keys in one Table Listed in Another Table  What are the foreign Keys in the Lyric Database?  Why Foreign Keys?  So we can combine tables!

Combining Tables  Why the need to combine tables? Why so many tables anyway?  So far used only one table at a time.  Different tables in our database  One-to-one relationships  Remember the first lecture – parent with one child  One-to-many relationships  One record can be related to many other records  What relates to records in the Titles table?  Many-to-many relationships  Want as little redundancy as possible  What happened if Artists, Titles, and Tracks were instead in one database?  Any redundancies?

Ways to combine tables  Cartesian Product  All possible combinations of rows and columns  Also called “Cross Join”  Joins  Cartesian Product… with Conditions  Different Types of Conditions  Foreign keys  Other (much later)

Cartesian Product  Set of all possible concatenated rows from tables A and B  First component from first table (A)  Second component from second table (B)  First table = “a” rows, Second table = “b” number of rows  Cartesian product = a x b rows  A = 6, B = 4?

Cartesian Product (2)  Genre x Titles?  Genre is a foreign key of Titles  Cartesian Product, so foreign keys don’t matter  Called a CROSS JOIN in SQL  SELECT * FROM Titles CROSS JOIN Genre;  Result?  Lots of info… / Too much info!!

Joins  Subset of the Cartesian Product  Similar (mathematical) operation, but only concatenates if a condition is met  Called the join condition or join predicate  Different types of join conditions  Different types of joins  Table A,B performs Cartesian Product  Only concatenates if join condition is true!

Types of Joins  Many types of Joins  We will cover some this week, some next week  Cross Joins  Named Column Joins  Inner Join  Equi-Join  Natural Joins  Next week  Outer join, LEFT, RIGHT SELF, …

Equi-Join  Joins – take Cartesian Product  Match a column  Remove other rows  Use a comma to select multiple tables  SELECT *  FROM Artists, Titles  WHERE Artists.ArtistID = Titles.ArtistID  Results?  What is the Join Condition?  No join condition = cross join!

Equi-Join (2)  SELECT *  From Artists, Titles  Where Artists.artistID = Titles.artistID;  Why do this?  Just Artist name and titles  SELECT Artistname, Title  FROM Artists, Titles  WHERE Artists.artistID = Titles.artistID;

Equi-Join (3)  Can also use ON keyword instead of WHERE  SELECT attribute_list  FROM A,B  WHERE join_condition;  SELECT attribute_list  FROM A JOIN B  ON join_condition;

Named Column Joins  Tired of typing the same column name twice for every WHERE condition in the Join?  Use Named Column Joins (the JOIN, USING keywords)  SELECT attribute_list  FROM A JOIN B USING(column_name)  Works for joining multiple columns  SELECT attribute_list  FROM A JOIN B USING (name1, name2, …)  SELECT artistname, title, FROM artists JOIN titles USING (artistID);  Don’t forget the parentheses!!

Named Column Joins (2)  Take care! There may be cases where columns are the same name, but different data!  Be alert – you may not get the answer you’re looking for  What about this query? Find all Customers under salesman “Bentley”  SELECT *  FROM Members JOIN SalesPeople  USING (LastName);  Where SalesPeople.Lastname = ‘Bentley’  Why is this wrong?

Named Column Joins (3)  Correct:  Select MEMBERS.Firstname, MEMBERS.Lastname, SalesPeople.Lastname  FrOM MEMBERS JOIN SALESPEOPLE  Using (salesid)  Where SalesPeople.Lastname = 'Bentley';  SalesID is the proper column to join on  Foreign Key of Members  Primary Key of SalesPeople  Many databases have common “address,” “id,” “name” fields  Make sure you’re joining on the correct columns!  When in doubt, don’t use named column join!

Qualified Table Names  Last example:  Select MEMBERS.Firstname, MEMBERS.Lastname, SalesPeople.Lastname  FrOM MEMBERS JOIN SALESPEOPLE  Using (salesid)  Where SalesPeople.Lastname = 'Bentley';  If we SELECT * on the join, we get multiple first and last names  From Members and SalesPeople  Put the table name before the column (and “.”) to specify, or qualify the name.  If there are multiple columns, SQL will call it ambiguous, and cause an error.

Table Aliases  Select MEMBERS.Firstname, MEMBERS.Lastname, SalesPeople.Lastname  FrOM MEMBERS JOIN SALESPEOPLE  Using (salesid)  Where SalesPeople.Lastname = 'Bentley';  Don’t want to type out full table names to qualify?  Use a Table Alias  SELECT M.Firstname, M.Lastname, S.Lastname  FROM Members M, SalesPeople S,  Where M.SalesID = S.SalesID

Table Aliases (2)  Remember Column Aliases?  Can use the AS Keyword to Create Table Aliases  SELECT A.ArtistName, A.ArtistID, T.Title  FROM Artists AS A, Titles AS T  WHERE A.ArtistID = T.ArtistID;

Examples  Is this a lot? Don’t worry!  Ex:  SELECT *  FROM Artists A, Titles T  WHERE A.ArtistID = T.ArtistID;  SELECT M.LastName, S.Studioname  FROM Members M, Studios S  WHERE M.SalesID = S.SalesID  What type of join is this?

Inner Join  Same as Equi-Join, but with different syntax.  SELECT attribute_list  FROM A INNER JOIN B ON join_condition;  Safer than Named Column Join  Doesn’t require the same fields  List the name of each track with its respective title  Answer?  What do we need?  Tables: Tracks, Titles, Keys: TitleID

Inner Join (2)  Answer:  SELECT tr.tracktitle, ti.title  FROM Tracks tr INNER JOIN Titles ti  ON (tr.titleID = ti.titleID);

Natural Joins  Not in textbook  No join condition specified  DBMS determines automatically what to join on  Matches on all fields that have the same names in both tables  Unpredictable – stay away!  SELECT attribute_list  FROM A NATURAL JOIN B;  Will find this in other texts

More on Foreign Keys  Column with values that are Primary Keys of another table  Examples: ArtistID in Titles Table  Other?  Can also protect Data base from anomalies  Try to use joins with foreign keys  Good practice  Most joins use foreign keys

Cross Referencing Tables  Note XrefArtistMembers table  Can allow an individual listed in the members table to be a member of any number of artists.  An artist can also have any number of members  Many-to-many relationship

Joining Multiple (more than 2) Tables  You can chain tables:  SELECT *  FROM A NATURAL JOIN B NATURAL JOIN C;  Why no join condition above?  SELECT *  FROM A JOIN B USING (a1) JOIN C USING(a2);

Joining Multiple Tables (2)  Inner Join:  SELECT *  FROM A INNER JOIN B ON A.n1 = B.n2 INNER JOIN C ON B.n3 = C.n4;  Equi-Join:  SELECT *  FROM A,B,C  WHERE A.n1 = B.n2 AND B.n3 = C.n4;

Joining Multiple Tables (3)  Why?  List all members of the band “The Neurotics’  List all members of “Confused”

Joining Multiple Tables (4)  Select M.Firstname, M.Lastname, A.Artistname, A.ArtistID  FrOM Artists A JOIN XrefArtistsMembers Using (ArtistID) JOIN Members M USING(Memberid)  Where Artistname = 'The Neurotics';

More Examples  Provide the first and last names of all members who have recorded at the studio “MakeTrax”  Solving  What tables are we using?  Start with Members, end with studios  Xrefartistsmembers, Titles  What keys match?

More Examples (2)  Answer:  SELECT DISTINCT m.firstname, m.lastname  FROM Members M JOIN XrefArtistsMembers X USING (memberID)  JOIN Titles t USING (artistID)  JOIN Studios s USING (studioID)  WHERE S.StudioName = ‘maketrax’;

Join Expressions  You can also use joins within parentheses, like mathematical expressions  Such as (x + y) * (a + b)  Ex:  SELECT *  FROM (A JOIN B USING(n1)) JOIN (C JOIN D USING(n2)) USING(n3)  More on this later…