Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Development Tools Database Foundations Joining Relational Data Between Tables in SQL Joining Tables and Aliasing

John MacDonald
John MacDonald
8,593 Points

I can't get my head around how this SQL Statement works?

I don't understand how we are able to retrieve the genres.name when it is from the movies table.

SELECT movies.name, genres.name FROM movies LEFT OUTER JOIN genres ON movies.genre_id = genres.id WHERE movies.id = 3;

If someone could explain this better it would help me alot!

Cheers!

1 Answer

Say you want to store some information about Movies. You start by putting all the information in one file, sometimes referred to as a Flat File. It has Movie Name, Movie Date, Movie Genre, Actor 1, Actor 2 etc If you have multiple movies with the same genre you are then repeating data which isn't the best solution. You want to normalise the data. You can split this into two tables: Movies Genres You can then relate a Genre to a Movie. To do this you can create a key column in the Genre Table and store this value in the Movie Table.

For example: Genre Id | Name 1 | Sci Fi 2 | Fantasy 3 | Action Etc

Now in your Movies table you will add a Foriegn Key, this is your link.

Movies Id | Name | genre_id 1 | Die Hard | 3

Now if you want to show all Action movies you create a Query that joins the two Tables together using the genre ids that match and use a WHERE clause to filter on Action i.e. 3

Because the two tables are joined you can pull in values from either to be returned by the Query:

TABLE.FIELD := genres.name

SELECT movies.name, genres.name FROM movies LEFT OUTER JOIN genres ON movies.genre_id = genres.id WHERE movies.id = 3;