【mssql】求一条sql

A表:id(varchar),switch(bit)

B表: id(varchar),switch2(bit)

需求:A.id = B.id 且 B.switch2 = 1的数据,或者A表的id不存在于B表时(A表有id,B表没这id)且 A.switch=1

我只能想到这样:

select * from A
join B on  ((A.id = B.id and B.switch2 = 1) or (?????? and A.switch = 1))
left join C表 ...省略

select * from A
left join (select id,isnull(switch2,0) as switch2 from B) B on A.id=B.id
where isnull(B.switch2,A.switch)=1

-- 首先,为了确保B表中,所有switch2有值,避免isnull时判断出错,将null值修正为0
-- 当B表所有id对应switch2有值时,与A表关联,则B表有ID必定有值,否则无对应ID则无值
-- 当B表有值,则取B表值,否则取A表值,最终结果都要是取值为1的,所以 isnull(B.swith2,A.switch)最简单

select * from A left join B on ( A.switch=1 or (A.id = B.id and B.switch2 = 1) );

试试

select * from A

join B as b1 on (A.id = B.id and B.switch2 = 1) 

left join B as b2 on(A.id = B.id and A.switch = 1)

where b2.id is null