mysql - 连接加倍结果的问题

标签 mysql sql

我在 Stack Overflow 上看到过几篇关于此问题的帖子,但似乎没有一个能给我一个我能理解的答案。

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

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

我首先尝试输出在中国有 start_port 的所有内容。我期望从我的 Record 关系中得到 3 个结果,因为这些是表中唯一以 China 开头的结果;但是,我在输出中收到 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

最佳答案

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

您已经知道从中国开始到美国结束的所有 SeaRoutes,但是您确实需要加入 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

关于mysql - 连接加倍结果的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55036804/

相关文章:

mysql - 向表中插入非重复数据

php - 使用 PHP 从 mysql db 中选择并回显单个字段

java - 复合主键太长?

sql - 使用 DATEDIFF() 的计算列

sql - 动态连接列的查询性能优化

python - 如何在 Python MySQL 查询中插入字符串?

php - Laravel - 碳时代

mysql - SQL 查询在主机服务器上不工作,但在本地工作

SQL Server 查询以更新具有相同名称的多行

忽略空字符串列的mysql group_concat