连接加倍结果的问题

时间:2019-03-07 05:42:01

标签: mysql sql

我已经在Stack Overflow上看到了几篇关于此的文章,但是似乎都没有一个我能理解的答案。

我正在尝试将几个关系合并在一起,以获取所有相关信息,以输出从中国开始到美国结束的所有路线。

SeaRoute关系中,start_portend_port被存储为INT,在Port关系中,pid对应于start_portend_port,并包含一个pcountry列。

我首先尝试输出在中国具有start_port的所有内容。我期望Record关系带来3个结果,因为这些是表中唯一以中国开头的结果;但是,我在输出处收到6条记录(如果我返回并审核表中的内容,所有结果似乎都翻了一番。)

尽管我想要正确的答案,但我更担心我对Inner Join和其他Join方法有基本的误解。我在做什么错了?

SELECT *
FROM Record
INNER JOIN Goods AS Go_data 
    ON Record.gid = Go_data.gid
LEFT JOIN SeaRoute AS SR 
    ON Record.rid = SR.rid
RIGHT JOIN (SELECT pid, pcountry AS starting_port_country
            FROM Port
            INNER JOIN SeaRoute AS SR ON Port.pid = SR.start_port
            WHERE Port.pcountry = 'China') 
            AS start_port_table ON SR.start_port = start_port_table.pid

1 个答案:

答案 0 :(得分:1)

从查询的外观来看,您希望在仅拥有所需路线的记录之间进行内部联接。

您知道所有始于中国并已结束于美国的SeaRoute,但是您确实需要像这样两次连接到Ports表:

SELECT  sr.rid,
        sp.pcountry AS starting_port_country,
        ep.pcountry AS end_port_country
FROM dbo.SeaRoute sr
    INNER JOIN dbo.Port sp ON sp.pid = sr.start_port
    INNER JOIN dbo.Port ep ON ep.pid = sr.end_port
WHERE   sp.pcountry = 'China'
    AND ep.pcountry = 'United States'

然后,您只需要将其加入到主查询中即可:

SELECT *
FROM Record
    INNER JOIN dbo.Goods AS Go_data     ON Record.gid = Go_data.gid
    INNER JOIN  
        (
            SELECT  sr.rid,
                    sp.pcountry AS starting_port_country,
                    ep.pcountry AS end_port_country
            FROM dbo.SeaRoute sr
                INNER JOIN dbo.Port sp ON sp.pid = sr.start_port
                INNER JOIN dbo.Port ep ON ep.pid = sr.end_port
            WHERE   sp.pcountry = 'China'
                AND ep.pcountry = 'United States'
        ) ports ON ports.rid = Record.rid

没有任何方法可以比此页面更清楚地向您解释联接:

https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins