添加条件到第二个左连接

时间:2017-08-07 22:13:00

标签: sql-server

请查看以下查询:

SELECT distinct a.*, coalesce (r.email,r2.email) as 'sign_in_email'
into #adobe_prep
FROM dbo.adobe 
left join 
dbo.registration r ON (a.user_id = r.up_user_id)
left join 
dbo.registration r2 ON (a.user_id = r2.entity_id)

我基本上尝试将a.user_id与r.up_user_id匹配,如果与up_user_id不匹配,则匹配entity_id。 但是,这个语句没有条件,所以我得到重复,因为有时a.user_id = r.up_user_id但是a.user_id = r2.entity_id(仅用于不同的值)。 你能帮忙添加条件,只有当a.user_id<>时才会出现第二个左连接。 r.up_user_id?

1 个答案:

答案 0 :(得分:1)

但你自己写了答案!尝试添加您用文字写的条件:

and a.user_id <> r.up_user_id

像这样:

select distinct a.*, coalesce (r.email,r2.email) as 'sign_in_email'
into #adobe_prep
from dbo.adobe 
          left join dbo.registration r ON (a.user_id = r.up_user_id)
          left join dbo.registration r2 ON (a.user_id = r2.entity_id and a.user_id <> r.up_user_id)