如何在 MySQL LEFT JOIN 中使用别名
我原来的查询是使用 WHERE 子句而不是 JOIN 进行连接。我意识到这并没有返回没有任何明星或类型的电影没有出现,所以我想我必须做一个 LEFT JOIN 才能显示每部电影。这是我原来的 SQL:
SELECT *
FROM movies m, stars s, stars_in_movies sm, genres g, genres_in_movies gm
WHERE m.id = sm.movie_id
AND sm.star_id = s.id
AND gm.genre_id = g.id
AND gm.movie_id = m.id
AND m.title LIKE '%the%'
AND s.first_name LIKE '%Ben%'
ORDER BY m.title ASC
LIMIT 5;
我尝试对电影进行 LEFT JOIN 我肯定做错了什么。
SELECT *
FROM movies m, stars s, stars_in_movies sm, genres g, genres_in_movies gm
LEFT JOIN movies m1 ON m1.id = sm.movie_id
LEFT JOIN movies m2 ON m2.id = gm.movie_id
AND sm.star_id = s.id
AND gm.genre_id = g.id
ORDER BY m.title ASC
LIMIT 5;
我得到 ERROR 1054 (42S22): Unknown column 'sm.movie_id' in 'on Clause'
很明显我做的连接是错误的,我只是不明白它是什么。
My original query is doing joins using the WHERE clause rather than JOIN. I realized that this was not returning movies that did not have any stars or genres did not show up so I think I have to do a LEFT JOIN in order to show every movie. Here is my original SQL:
SELECT *
FROM movies m, stars s, stars_in_movies sm, genres g, genres_in_movies gm
WHERE m.id = sm.movie_id
AND sm.star_id = s.id
AND gm.genre_id = g.id
AND gm.movie_id = m.id
AND m.title LIKE '%the%'
AND s.first_name LIKE '%Ben%'
ORDER BY m.title ASC
LIMIT 5;
I tried to do a LEFT JOIN on movies I'm definitely doing something wrong.
SELECT *
FROM movies m, stars s, stars_in_movies sm, genres g, genres_in_movies gm
LEFT JOIN movies m1 ON m1.id = sm.movie_id
LEFT JOIN movies m2 ON m2.id = gm.movie_id
AND sm.star_id = s.id
AND gm.genre_id = g.id
ORDER BY m.title ASC
LIMIT 5;
I get ERROR 1054 (42S22): Unknown column 'sm.movie_id' in 'on clause'
so clearly I'm doing the join wrong, I just don't see what it is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要将逗号运算符与 JOIN 混合使用 - 它们具有不同的优先级! 手册中甚至有关于此的警告:
试试这个:
Don't mix the comma operator with
JOIN
- they have different precedence! There is even a warning about this in the manual:Try this instead:
您应该将与 JOIN 相关的条件放在同一个 ON 子句中。但是,对于上述问题,您应该使用以下查询:
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:
人们警告说这是一次黑客攻击。
连接右侧的表,其中包含您要比较的列。
People warn that this is a hack.
Join with the right table, which has the columns you are comparing.