【问题标题】:Joining two tables using third as linking table, including null entries使用第三个作为链接表连接两个表,包括空条目
【发布时间】:2012-09-08 15:43:55
【问题描述】:

我查看了许多类似的问题,但尚未偶然发现/找到以下问题的正确解决方案。

给定以下三个表:

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 = ?

这可行,但会排除阶段中不匹配的所有帐户条目。

我需要有account.bill_acct=stage.bill_acct 的所有行,在它存在的地方为stage.account_class 附加一列,否则为null。

多个连接总是让我失望。

想法?

【问题讨论】:

  • 我相信您所寻找的只是舞台上的 LEFT JOIN 而不是常规的 (INNER) JOIN

标签: sql oracle join ansi-sql


【解决方案1】:

尝试左连接:

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 = ?

【讨论】:

  • 谢谢,(左连接)就是这样。
【解决方案2】:

由于要提取独立于舞台表的所有信息(舞台表上没有匹配项),最适合使用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, 之前的所有记录,即使右表中没有匹配项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多