Mysql – How to select two columns from two different tables using foreign keys from another third table

join;MySQLselect

I am using MYSQL and here is the schema that I have:

Here is my first table user

+-----+------------------+
| id  | name             |
+-----+------------------+
| 101 | Daniel Radcliffe |
| 102 | Elijah Wood      |
| 103 | Robert Downey Jr |
+-----+------------------+

Here is my second table movie

+----+---------------------+
| id | name                |
+----+---------------------+
|  1 | Harry Potter 1      |
|  2 | Harry Potter 2      |
|  3 | Harry Potter 3      |
|  4 | Lord of the Rings 1 |
|  5 | Lord of the Rings 2 |
|  6 | Lord of the Rings 3 |
|  7 | Iron Man 1          |
|  8 | Iron Man 2          |
+----+---------------------+

Here is my last table list

+---------+----------+ 
| user_id | movie_id | 
+---------+----------+ 
|     101 |        1 | 
|     101 |        2 | 
|     101 |        3 | 
|     102 |        4 | 
|     102 |        5 | 
|     102 |        6 | 
|     103 |        7 | 
|     103 |        8 | 
+---------+----------+ 

Now I want to display name and movie side by side something like this:

+------------------+--------------------+
| Daniel Radcliffe | Harry Potter 1     |
| Daniel Radcliffe | Harry Potter 2     |
| Daniel Radcliffe | Harry Potter 3     |
| Elijah Wood      | Lord of the Rings 1|
| Elijah Wood      | Lord of the Rings 2|
| Elijah Wood      | Lord of the Rings 3|
| Robert Downey Jr | Iron Man 1         |
| Robert Downey Jr | Iron Man 2         |
+------------------+--------------------+

The list table has foreign keys for user_id and movie_id which reference user.id and movie.id respectively. So how can I use JOINs to display the above data.

Best Answer

SELECT user.name, movie.name
FROM user, movie, list
WHERE list.user_id  = user.id
  AND list.movie_id = movie.id
ORDER BY 1,2;

Or, if you need to see the word JOIN in the query text

SELECT user.name, movie.name
FROM user
JOIN list  ON list.user_id  = user.id
JOIN movie ON list.movie_id = movie.id
ORDER BY 1,2;