数据库
首页 > 数据库> > mysql – SQL外连接 – 执行不当

mysql – SQL外连接 – 执行不当

作者:互联网

我正在学习SQL,我已经学习了复数的基础课程,现在我通过Treehouse使用MySQL,他们通过MySQL服务器设置了虚拟数据库.一旦我的培训完成,我将每天在工作中使用SQLServer.

昨天我遇到了两个部分的挑战,我遇到了一些麻烦.
挑战中的第一个问题是:

“We have a ‘movies’ table with a ‘title’ and ‘genre_id’ column and a
‘genres’ table which has an ‘id’ and ‘name’ column. Use an INNER JOIN
to join the ‘movies’ and ‘genres’ tables together only selecting the
movie ‘title’ first and the genre ‘name’ second.”

理解如何正确设置JOINS对我来说有点混乱,因为概念看起来很简单,但就像烹饪一样,执行就是一切 – 而且我做错了.在经过一些试验和错误,工作以及重复树屋解释几次之后,我能够想出这个;这是我如何通过Treehouse接受的答案解决第一个问题:

SELECT movies.title, genres.name FROM movies INNER JOIN genres ON movies.genre_id = genres.id;

– 但 –

下一个挑战的问题我没有那么成功,而且我不确定我哪里出错了.我真的希望通过JOINS变得更好,挑选所有聪明人的大脑是我能想到的最好的方法来解释这个特定的(我确定,对你们来说很可怜)问题.谢谢你的帮助,这里是我难倒的地方:

“Like before, bring back the movie ‘title’ and genre ‘name’ but use
the correct OUTER JOIN to bring back all movies, regardless of whether
the ‘genre_id’ is set or not.”

这是我提出的最接近(?)的解决方案,但我在这里做错了(可能很多)错了:

SELECT movies.title, genres.name FROM movies LEFT OUTER JOIN genres ON genres.id;

我最初尝试了这个(下面),但是当它不起作用时,我决定删除语句的最后部分,因为在需求标准中提到我需要一个不关心genre_id是否设置的数据集电影表是否:

SELECT movies.title, genres.name FROM movies LEFT OUTER JOIN genres ON movies.genre_id = genres.id;

我知道这是完全noob的东西,但就像我说的,我正在学习,我在Stack和整个互联网上研究的问题不一定适合同样的问题.我非常感谢您的专业知识和帮助.感谢您花时间阅读本文,并在您选择的时候提供帮助!

解决方法:

你的解决方案正确:

SELECT movies.title, genres.name 
    FROM movies 
        LEFT OUTER JOIN genres ON movies.genre_id = genres.id

这是我的解释:

事实上,当你告诉“左连接”或“左外连接”时,

it’s not that “You don’t care if genre_id is set in the movies table or not”,

but “You want all genres of each movie to be shown, however, you don’t care if genre_id is not set in the movies table for some records; just show the movie in these cases [and show ‘genre = NULL’ for those records]”

通常,在“左连接”中,您需要:

all the records of the left table, with their corresponding records in the other table, if any. Otherwise with NULL.

在您的示例中,将显示以下两组记录:

1- All the movies which have been set to a genre
(give movie.title, Genres.name)

2- All other movies [which do not have a genre, i.e., genre_id = NULL]
(give movie.title, NULL)

示例(使用左连接):

Title, Genre
--------------
Movie1, Comedy
Movie1, Dramma
Movie1, Family
Movie2, NULL
Movie3, Comedy
Movie3, Dramma
Movie4, Comedy
Movie5, NULL

示例(使用内部联接):

Title, Genre
--------------
Movie1, Comedy
Movie1, Dramma
Movie1, Family
Movie3, Comedy
Movie3, Dramma
Movie4, Comedy

标签:mysql,join,sql,left-join,outer-join
来源: https://codeday.me/bug/20190623/1274144.html