sql - 使用第三个表作为链接表连接两个表,包括空条目

标签 sql oracle join ansi-sql

我已经研究过许多类似的问题,但尚未偶然发现/找到以下问题的正确解决方案。

给出以下三个表:

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。

多重连接总是让我困惑。

想法?

最佳答案

尝试左连接:

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

关于sql - 使用第三个表作为链接表连接两个表,包括空条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12332128/

相关文章:

mysql - 多登录区

oracle - 将oracle数据库导出到另一台服务器

SQL建表错误

arrays - 加入 inet[] 到 inet

VLOOKUP 的 SQL 版本

sql - 在 where 子句中切换大小写/If

mysql - MySQL 触发器可能会静默失败吗?

php - 在 MySQL 数据库中搜索相关/包含多个标签记录的书签

database - oracle数据库的sqlplus如何列出一个表中的所有数据?

MySQL 左连接第一个和第二个结果并作为一行返回