Pregunta

I was practising with an example that I was creating like the one below (where I was thinking about a movie being able to belong to many categories and a category being able to belong to have many subcategories).

Not sure if chaining two many-to-many relationships is correct (I split them up in several one to many relationships), but when I'm making a query I'm getting pretty weird results.

Any clue how could I get movie title and genre name for all movies, even the ones without genre name? I'm using a query similar to this but it's not returning those titles :S

If I stop after the 1st many-to-many relationship, the results seem correct but once I add the 2nd relationship (with the query below), I don't receive anything... any suggestion pls?

SELECT movie.title, genre.name 
FROM movie 
LEFT OUTER JOIN movie_genre 
ON (movie.movie_id = movie_genre.movie_id) 
JOIN genre 
ON (genre.genre_id = movie_genre.genre_id) 
JOIN genre_subgenre 
ON (genre_subgenre.genre_id = genre.genre_id) 
JOIN subgenre 
ON (subgenre.subgenre_id = genre_subgenre.subgenre_id) 



+++++++++++++++++ 
+ Movie ID (PK) + 
+ Movie Title + 
+++++++++++++++++ 
| 
| 
| 
+++++++++++++++++ 
+ Movie ID (FK) + 
+ Genre ID (FK) + 
+++++++++++++++++ 
| 
| 
| 
+++++++++++++++++++ 
+ Genre ID (PK) + 
+ Genre Name + 
+++++++++++++++++++ 
| 
| 
| 
++++++++++++++++++++ 
+ Genre ID (FK) + 
+ Subgenre ID (FK) + 
++++++++++++++++++++ 
| 
| 
| 
+++++++++++++++++++++++++ 
+ Subrenre ID (PK) + 
+ Subgenre Name (FK) + 
+++++++++++++++++++++++++
¿Fue útil?

Solución

Let me propose sample data to see if I get it right:

  • Movies: "Saw", "Twilight", "Platoon"
  • Genre: "Thriller", "Comedy", "Action"
  • Subgenre: "Hollywood", "French", "Italian"

If this picture is correct then your design may be wrong as there is no relationship between Movie and Subgenre. That told, try this

SELECT movie.title, genre.name 
FROM movie 
LEFT OUTER JOIN movie_genre 
ON (movie.movie_id = movie_genre.movie_id) 
JOIN genre 
ON (genre.genre_id = movie_genre.genre_id) 
LEFT OUTER JOIN genre_subgenre 
ON (genre_subgenre.genre_id = genre.genre_id) 
LEFT OUTER JOIN subgenre 
ON (subgenre.subgenre_id = genre_subgenre.subgenre_id) 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top