问题
Need help in creating a SQL query. Little confused so asking question. Here is the situation:
I have one table say EmpInfo:
EmpFirstName, EmpLastName, EmpID, EmpGender, EmpDOB, EmpAddress
Table2 EmpMasterID:
EmpID1, EmpId2, AbsoluteEmpID
EmpInfo contains sample data:
EmpFirstName | EmpLastName | EmpID | EmpGender | EmpDOB | EmpAddress
First1 | Last1 | 10 | M | 1/1/92 | Addr1
First2 | Last2 | 20 | F | 1/12/92 | Addr2
First3 | Last3 | 30 | F | 1/12/94 | Addr3
First4 | Last4 | 40 | M | 1/2/94 | Addr4
First5 | Last5 | 60 | M | 1/1/91 | Addr5
First6 | Last6 | 70 | F | 1/12/92 | Addr6
First7 | Last7 | 80 | F | 1/12/95 | Addr7
First8 | Last8 | 90 | M | 1/2/97 | Addr8
EmpMasterID sample data:
EmpID1 | EmpId2 | AbsoluteEmpID
10 | 20 | 10
60 | 70 | 60
Now I have to join these 2 tables and get the following columns:
EmpID, EmpFirstName, EmpLastName, AbsoluteEmpID
The value of AbsoluteEmpID will be picked up from the EmpMasterID table if EmpInfo.EmpID = EmpMasterID.EmpID1 OR EmpInfo.EmpID = EmpMasterID.EmpID2
Otherwise the value of AbsoluteEmpID will be EmpID itself.
Please help.
Thanks.
回答1:
This will join either on EmpID1
or on EmpID2
. If both fails, left join
ensures you get a row with null
and then you just replace null
with empid
:
select ei.EmpID,
ei.EmpFirstName,
ei.EmpLastName,
isnull(em.AbsoluteEmpID, ei.EmpID) as AbsoluteEmpID
from EmpInfo ei
left join EmpMasterID em on ei.empid = em.EmpID1 or ei.empid = em.EmpID2
回答2:
Should be based on an inner join
update EmpInfo
INNER JOIN EmpMasterID On (EmpInfo.EmpID = EmpMasterID.EmpID1
OR EmpInfo.EmpID = EmpMasterID.EmpID2)
SET EmpID = AbsoluteEmpID
回答3:
Why don't you just want this?
SELECT ei.EmpID, ei.EmpFirstName, ei.EmpLastName, em.AbsoluteEmpID
FROM EmpMasterID em JOIN
EmpInfo ei
ON ei.EmpID = ei.AbsoluteEmpID;
I don't see what OR
has to do with this query.
来源:https://stackoverflow.com/questions/40706849/sql-join-query-with-or-clause