I need to get data from 3 different tables. I know the basics about JOINs but when it comes to more complicated queries like getting data from 3 or more tables using JOIN I get a little confused and I just start playing with the queries writing what make sense to me, like the next one:
SELECT movies.imdbID,
movies.title,
movies.year,
movie_ratings.votes,
movie_ratings.total_value,
movie_ratings_external.votes,
movie_ratings_external.total_value
FROM movies, movie_ratings_external
LEFT JOIN movie_ratings ON movie_ratings.imdbID = movie_ratings_external.imdbID
WHERE movies.imdbID = movie_ratings_external.imdbID
ORDER BY movie_ratings.votes DESC, movie_ratings_external.votes DESC
LIMIT 30
This query works. I get the selected fields from the correct tables and ordered the right way, but I think I’m mixing up things (like regular querying two tables and JOINing between two tables) and I’m sure theres a better/more efficient way to accomplish the same purpouse.
Any DB geek available?
Modified your query just a tad bit. Everything else was pretty much spot on.
I am not exactly sure what you call a “regular query” but Joins are pretty much the very basic part of a regular query.
In your old query, this part
FROM movies, movie_ratings_externalwas basically aCROSS JOIN. Replaced it with aJOIN(i used aLEFT JOINassuming that you always wanted to return all the movies but basic intention was that the CROSS JOIN with the filtering in the WHERE is a LOT more inefficient because you are manipulating more ROWS – especially unnecessary ones)Think of it this way. Every Join statement in your SELECT returns a set of row which are then JOINED with the next table in the JOIN. The idea should be to try an filter rows progressively with each join as far as possible so that you arent getting unnecessary tuples. Thats where the ON statements come in.
Removed
Hope that helps!!