如何根据条件加入此查询?

时间:2016-09-27 08:19:16

标签: sql join left-join inner-join

我有一个像下面这样的查询来加入6表。

select     usr.userid,usr.firstName,usr.middleName,usr.lastName,nuser.GRAND_FATHER_NAME,nco    untry.NAME_AR,ncountry.NAME_EN,ncase.START_DATE 
from  User_ usr 
inner join TBL_NAFETHAH_USER nuser 
On nuser.USER_ID = usr.userId 
inner join TBL_NAFETHAH_COUNTRY ncountry 
on nuser.NATIONALITY = ncountry.ID
inner join TBL_NAFETHAH_CASE ncase 
on usr.userId = ncase.inmate_id 
inner join TBL_NAFETHAH_CASE_STATUS ncasestatus 
ON ncase.CASE_STATUS_ID = ncasestatus.CASE_STATUS_ID
and ncasestatus.CASE_STATUS IN (1,2)) 
inner join TBL_NAFETHAH_CASE_STAGE ncasestage 
on ncasestage.CASE_STAGE_ID = ncase.CASE_STAGE_ID                   
inner join TBL_NAFETHAH_USER_IDENTIFICATION uident 
on ( (usr.userId = uident.USER_ID and uident.ID_TYPE = 1) or (usr.userId = uident.USER_ID and uident.ID_TYPE = 2) )   
inner join TBL_NAFETHAH_LOOKUP_VALUE nlookup 
on nlookup.LOOKUP_KEY = uident.ID_TYPE 
and nlookup.CATEGORY_ID = 9
inner join TBL_NAFETHAH_LOOKUP_VALUE nlookup2 
on nlookup2.LOOKUP_KEY = ncasestage.CASE_STAGE 
and nlookup2.CATEGORY_ID = 15
where  nuser.MAKE_PUBLIC = 1

我想在这一行中增加一个条件

         inner join TBL_NAFETHAH_USER_IDENTIFICATION uident on ( (usr.userId = uident.USER_ID and uident.ID_TYPE = 1) or (usr.userId = uident.USER_ID and uident.ID_TYPE = 2) )   

如果不符合这个条件,即空(usr.userId = uident.USER_ID and uident.ID_TYPE = 1) or (usr.userId = uident.USER_ID and uident.ID_TYPE = 2) m,那么我必须添加另一个条件(usr.userId = uident.USER_ID),如果它返回多行,则只占第一行。

如何实现它?

1 个答案:

答案 0 :(得分:0)

如果要忽略TBL_NAFETHAH_USER_IDENTIFICATION表中缺少的记录,则INNER JOIN一个子查询返回满足条件的第一条记录,并使用有用的 ORDER BY

inner join 
(
    SELECT TOP(1) * FROM TBL_NAFETHAH_USER_IDENTIFICATION uident 
    WHERE usr.userId = uident.USER_ID  --AND ID_TYPE IN(1, 2)
    ORDER BY ID_TYPE 
)
uident ON usr.userId = uident.USER_ID 

如果要包含TBL_NAFETHAH_USER_IDENTIFICATION表中没有匹配的记录,则LEFT OUTER JOIN一个子查询返回符合条件的第一条记录,其中包含有用的 ORDER BY

left outer join 
(
    SELECT TOP(1) * FROM TBL_NAFETHAH_USER_IDENTIFICATION uident 
    WHERE usr.userId = uident.USER_ID ID_TYPE IN(1, 2)
    ORDER BY <SomeValue>
 )
 uident ON 1=1

注意:如果每个用户的TBL_NAFETHAH_USER_IDENTIFICATION中总会有一条记录,那么您可以按ID_TYPE排序并取第一行。如果1和2是ID_TYPE中的前两个值,则这将保证如果存在类型1或2,则它将首先出现。如果您的类型为0,-1,A,B等,则必须通过另一个子查询添加虚拟排名列。