首页 > 解决方案 > SQL:了解 FULL OUTER JOIN 的工作原理

问题描述

我有名为 Movie、Genre 和 Keyword 的表,我从中创建了一个名为“genkeyword”的视图。视图 'genkeyword' 有很多元组,因此可以在DB Fiddle访问它。

以下查询计算 genkeyword 中的电影与哈利波特相同的类型的频率以及 genkeyword 中的电影与哈利波特相同的关键词的频率。然后,它使用完全外连接组合两个查询的结果。

SELECT
    *
FROM
    (
        SELECT
            title,
            year,
            count(distinct genre) as genre_freq
        FROM
            genkeyword
        where
            (
                genre in (
                    select
                        genre
                    from
                        genkeyword
                    where
                        title = 'Harry Potter and the 
Deathly Hallows'
                )
            )
            AND title <> 'Harry Potter and the Deathly Hallows'
        group by
            title,
            year
    ) a 
    FULL OUTER JOIN (
        select
            title,
            year,
            count(distinct keyword) as keyword_freq
        FROM
            genkeyword
        where
            keyword in (
                select
                    keyword
                from
                    genkeyword
                where
                    title = 'Harry Potter and 
the Deathly Hallows'
            )
            and title <> 'Harry Potter and the Deathly Hallows'
        group by
            title,
            year
    ) b ON b.title = a.title;

上述查询的输出如下:

title               |   year    |   genre_freq   |    title    |    year    | keyword_freq

Cinderella              2015         2              Cinderella      2015        2   

Enchanted               2007         1              Enchanted       2007        3

How to train your dragon  2010       2               null           null       null
The Shape of Water        2017       2        The Shape of Water    2017       1       

我知道对于两个结果集 A 和 B,完全外连接输出 A 和 B 中匹配的行,以及 A 中没有匹配行 B 中的行和 B 中没有匹配的行在 A 中有匹配的行。

但是,在输出的第三行(电影是“如何训练你的龙”),为什么 title 和 year 属性有空值?我知道对于keyword_freq 的值将是空的,因为这部电影没有任何与哈利波特相同的关键字,但标题和年份属性不会分别具有“如何训练你的龙”和2010 的值吗?

任何见解都值得赞赏。

标签: sqlpostgresql

解决方案


推荐阅读