使用第三个表作为连接表将两个表连接在一起,包括空条目。

5

我看过很多类似的问题,但还没有找到下面问题的正确解决方案。

给出以下三张表:

account
    profile_id number (nullable)
    bill_acct varchar
    status varchar (nullable)
    remarks varchar (nullable)


stage
    ecpd_profile_id number (nullable)
    bill_account varchar (nullable)
    account_class varchar (nullable)

profile
    ecpd_profile_id number
    reg_prof_id number

我需要创建一个或多个联接来选择以下内容:

account.bill_act, account.status, account.remarks, stage.account_class

在哪里

profile.ecpd_profile_id = (given number)

account.profile_idprofile.reg_prof_id是等价的。

stage.ecpd_profile_idprofile.ecpd_profile_id是等价的。

stage.bill_acctaccount.bill_acct是等价的。

我已经尝试了以下方法...

select
    account.bill_acct,
    account.status,
    account.remarks,
    stage.account_class
from
    registration_account account
        join registration_profile profile
            on account.profile_id = profile.reg_prof_id
        join acct_stg stage
            on stage.ecpd_profile_id = profile.ecpd_profile_id
                and stage.bill_acct = account.bill_acct
where
    profile.ecpd_profile_id = ?

此方法可行,但排除了在stage表中没有匹配项的所有账户条目。

我需要所有满足account.bill_acct=stage.bill_acct条件的行,并在存在stage.account_class时添加一个额外的列,否则为null。

多个联接总是让我感到困惑。

有什么想法吗?


1
我相信你所需要的是在stage上进行LEFT JOIN而不是常规(INNER)JOIN。 - WuHoUnited
2个回答

7

尝试使用左连接:

select
    account.bill_acct,
    account.status,
    account.remarks,
    stage.account_class
from
    registration_account account
    left join registration_profile profile
            on account.profile_id = profile.reg_prof_id
    left join acct_stg stage
            on stage.ecpd_profile_id = profile.ecpd_profile_id
                and stage.bill_acct = account.bill_acct
where
    profile.ecpd_profile_id = ?

谢谢,那个(LEFT JOIN)就是它了。 - David Nedrow

3

如果您希望提取与阶段表无关的所有信息(在阶段表中没有匹配),则最适合使用以下方式的LEFT JOIN

SELECT
    account.bill_acct,
    account.status,
    account.remarks,
    stage.account_class
FROM
    registration_account account
        JOIN registration_profile profile
            ON account.profile_id = profile.reg_prof_id
       LEFT JOIN acct_stg stage
            ON stage.ecpd_profile_id = profile.ecpd_profile_id
                and stage.bill_acct = account.bill_acct
WHERE
    profile.ecpd_profile_id = ?

LEFT JOIN返回左表中所有记录或者LEFT JOIN之前的所有记录,即使右表中没有匹配的记录。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接