Download presentation
Presentation is loading. Please wait.
Published byChester McCoy Modified over 8 years ago
1
CS 122: Lecture 3 Joins (Part 1) Tarik Booker CS 122 California State University, Los Angeles October 7, 2014
2
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
3
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!
4
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?
5
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)
6
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?
7
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!!
8
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!
9
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, …
10
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!
11
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;
12
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;
13
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!!
14
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?
15
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!
16
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.
17
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
18
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;
19
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?
20
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
21
Inner Join (2) Answer: SELECT tr.tracktitle, ti.title FROM Tracks tr INNER JOIN Titles ti ON (tr.titleID = ti.titleID);
22
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
23
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
24
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
25
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);
26
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;
27
Joining Multiple Tables (3) Why? List all members of the band “The Neurotics’ List all members of “Confused”
28
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';
29
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?
30
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’;
31
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…
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.