我已经研究过许多类似的问题,但尚未偶然发现/找到以下问题的正确解决方案。
给出以下三个表:
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_id
和 profile.reg_prof_id
等效
stage.ecpd_profile_id
和 profile.ecpd_profile_id
等效
stage.bill_acct
和 account.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/