我正在尝试编写一个如下所示的查询。
select t1.t1c1, t1.t1c2, t2.t2c3, t2.t2c4
from table1 t1
left outer join (select top 1 t2c1, t2c2, t2c3, t2c4 from table2
where t2c5 in (select t3c1 from table3 t3
where **t3c2 = t1.t1c2 and t3c3 = t1.t1c3**) t2
on t1.t1c1 = t2.t2c1 and t1.t1c2 = t2.t2c2
SQL Server不允许的是上面突出显示的文本-即在table3子查询中引用table1的列。有没有办法做到这一点?我知道这可能不是最佳方法,还有其他方法可以实现吗?
你似乎确实想要outer apply
。我认为它看起来像这样:
select t1.t1c1, t1.t1c2, t2.t2c3, t2.t2c4
from table1 t1 outer apply
(select top 1 t2c1, t2c2, t2c3, t2c4
from table2
where t2c5 in (select t3c1
from table3 t3
where t3c2 = t1.t1c2 and t3c3 = t1.t1c3
) and
t1.t1c1 = t2.t2c1 and t1.t1c2 = t2.t2c2
) t2;
APPLY
与之相关的子查询非常相似,除了它位于FROM
子句中并且可以返回多列和多行。
注意:使用ORDER BY
时,您应该使用TOP
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句