DavidSzczesniak
1/18/2018 - 2:45 PM

Joining Two Tables

This allows us to show information from two different tables rather than one.

\!h Example 1: See how many albums we own by each artist
SELECT artist_name, album_name FROM artist INNER JOIN album 
USING (artist_id); -- USING indicates which column holds the relationship between the two tables

\!h Example 2: List track names for all the albums in the database
SELECT track_name, album_name FROM album INNER JOIN track
USING (artist_id, album_id); -- two USING parameters this time

\!h Example 3: sort previous example, albums alphabetically and tracks in the order they'd occur in their album
SELECT track_name, album_name FROM album INNER JOIN track
USING (artist_id, ablum_id)
ORDER BY album_name, track_id;

\!h Example 4: Which tracks you've played and when
SELECT played, track_name FROM 
track INNER JOIN played USING (artist_id, album_id, track_id)
ORDER BY track.artist_id, track.album_id, track_track_id, played; 
-- preceding the ids with 'track.' because there are 2 of each, 1 in each table
-- results sorted by artist, then album, then track, and then the play date and time

\!h With the ON keyword instead:
SELECT * FROM orders
JOIN subscriptions
ON orders.subscription_id = subscriptions.subscription_id;