Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

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

Alex Hedley
Alex Hedley
16,378 Points

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;