mysql - SQL 外部连接 - 执行不当

标签 mysql sql join left-join outer-join

我正在学习 SQL,我已经学习了 pluralsight 的基础类(class),现在我正在通过 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 让我有点困惑,因为这些概念看起来很简单,但就像在 cooking 中一样,执行就是一切——而我做错了。我能够在反复试验、工作并重新观看 Treehouse 解释几次后弄清楚这一点;这是我如何解决第一个问题,并给出了 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;

我知道这是完全菜鸟的东西,但就像我说的,我正在学习,我在 Stack 和整个 Internet 上研究的问题不一定适契约(Contract)一个问题。我非常感谢您的专业知识和帮助可以借鉴。感谢您抽出宝贵的时间阅读本文,如果您愿意的话,也可以提供帮助!

最佳答案

您的解决方案是正确的:

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

这是我的解释:

当你说“Left join”或“left outer join”时,其实,

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 - SQL 外部连接 - 执行不当,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30332197/

相关文章:

php, "thread safe"SQL操作

mysql - 将文本文件导入 MySql

mysql - 为 00.0 指定 float 大小

php - 没有索引导出/导入 5000 万行数据库?

php - 查询未选择表中的所有行

php - 如何通过 PHP 创建 PDF,其中数据是从 MySQL 收集的,并且是富文本格式

mysql - 在 VB 中从 MySQL 数据库获取第一个条目

mysql - 统计查询花费的时间

mysql 使用同一表中的行作为条件?

连接时可能带有空值的 MySQL 查询