select id,field1,field2,field3 from t1
left join (select id,field4,field5 from t2 where 条件) on t1.id=t2.id
where ...
问:
条件:这里由于t2表记录比较多,条件直接用t2的id=t1的id怎么写
在你所写括号后面加个别名 如e通过e.id的方式调用
left join 关联,是需要在 on 中指定关联条件,你写得这个就可以使用了,但是关联查询,无法引用所关联的内容作为查询条件
你可以使用 cross apply/outer apply 来实现
select * from t1
cross apply (
select * from t2 where id=t1.id
) t2
但是相对来说,apply 的效率没有 join 高
select id,field1,field2,field3 from t1
left join (select id,field4,field5 from t2 where 条件) on t1.id=t2.id
where ...
尽量把不使用子查询, left join 直接写 left join t2 on t1.id=t2.id, 把t2的where 条件写在外边,而且把t2的大筛选写在最后:
select id,field1,field2,field3 from t1
left join t2 on t1.id=t2.id
where ... and t2 (t2,条件写最后)