How to use aliases with MySQL LEFT JOIN
Maybe ugly, But the way it will work is here. Beware this is ugly and lot of people is giving warning about this kind of hacks
SELECT *
FROM movies m, stars_in_movies sm LEFT JOIN movies m1 ON m1.id = sm.movie_id, stars s
ORDER BY m.title ASC
LIMIT 5;
when using joins, you must do the join with the right table which have the columns you are comparing.
Don't mix the comma operator with JOIN
- they have different precedence! There is even a warning about this in the manual:
However, the precedence of the comma operator is less than of INNER JOIN, CROSS JOIN, LEFT JOIN, and so on. If you mix comma joins with the other join types when there is a join condition, an error of the form
Unknown column 'col_name' in 'on clause'
may occur. Information about dealing with this problem is given later in this section.
Try this instead:
SELECT *
FROM movies m
LEFT JOIN (
stars s
JOIN stars_in_movies sm
ON sm.star_id = s.id
) ON m.id = sm.movie_id AND s.first_name LIKE '%Ben%'
LEFT JOIN (
genres g
JOIN genres_in_movies gm
ON gm.genre_id = g.id
) ON gm.movie_id = m.id
WHERE m.title LIKE '%the%'
ORDER BY m.title ASC
LIMIT 5;
You should put your conditions related to your JOINs in the same ON clause. However, for your above problem, you should use the following query:
SELECT *
FROM movies m
LEFT JOIN stars_in_movies sm ON sm.movie_id = m.id
JOIN stars s ON sm.star_id = s.id
LEFT JOIN genres_in_movies gm ON gm.movie_id = m.id
JOIN genres g ON gm.genre_id = g.id
ORDER BY m.title ASC
LIMIT 5;