我在下面有2张桌子
Paam Table
AssignmentID PersonID AssignmentType
300000014199240 300000014199145 E
300000014199174 300000014199145 ET
Par Table
ASGResponsID AssignmentID PersonID Responsibility_Type
300000015244074 300000014199240 300000014199145 RC_HR_BP
300000015242351 300000014199240 300000014199145 RC_HR_BP
300000015244070 300000014199240 300000014199145 RC_HR_BP
我想加入这两个表并获得如下输出
PersonID Responsiblity_Type
300000014199145 RC_HR_BP
我正在使用以下查询
select
par.PersonID, par.Responsibility_Type
from
per_all_assignments_m paam, per_asg_responsibilities par
where
sysdate between nvl(paam.effective_start_date,sysdate) and
nvl(paam.effective_end_date,sysdate)
and paam.assignment_type='E'
and paam.assignment_id = par.assignment_id(+)
and paam.person_id = '300000014199145';
相反,我得到如下输出
PersonID Responsiblity_Type
300000014199145 RC_HR_BP
300000014199145 RC_HR_BP
300000014199145 RC_HR_BP
尽管使用了左外部联接,但我得到了多行,为什么会这样?
有人可以帮我理解吗?
谢谢, 湿婆
答案 0 :(得分:0)
首先使用具有正确语法的常规join
:
select par.PersonID, par.Responsibility_Type
from per_all_assignments_m paam join
per_asg_responsibilities par
on paam.assignment_id = par.assignment_id and
paam.person_id = par.person_id -- presumably also needed for the join
where sysdate between nvl(paam.effective_start_date, sysdate) and
nvl(paam.effective_end_date, sysdate) and
paam.assignment_type = 'E' and
paam.person_id = '300000014199145';
您对外部联接的意图可能是:
select par.PersonID, par.Responsibility_Type
from per_asg_responsibilities par left join
per_all_assignments_m paam
on paam.assignment_id = par.assignment_id and
paam.person_id = par.person_id and
sysdate between nvl(paam.effective_start_date, sysdate) and
nvl(paam.effective_end_date, sysdate) and
paam.assignment_type = 'E' and
where par.person_id = '300000014199145';
答案 1 :(得分:0)
根据您的数据,您将获得正确的结果。 par表中的所有三行都具有相同的assignmentId(300000014199240),因此无论连接语法如何,查询都会返回该行。
添加“独特”子句将为您提供所需的结果。
select DISTINCT
par.PersonID, par.Responsibility_Type
from
per_all_assignments_m paam, per_asg_responsibilities par
where
sysdate between nvl(paam.effective_start_date,sysdate) and
nvl(paam.effective_end_date,sysdate)
and paam.assignment_type='E'
and paam.assignment_id = par.assignment_id(+)
and paam.person_id = '300000014199145';
我在http://sqlfiddle.com/#!4/d7b7f/8的SQL小提琴中进行了设置。注意:我删除了日期字段引用,因为您没有为我们提供这些数据,但它不会根据您描述问题的方式影响结果。