复杂SQL使用前1条记录加入子查询

时间:2016-02-27 03:27:26

标签: sql sql-server join

我试图写一个类似下面的查询。

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的列。 有没有办法实现这个目标? 我知道这可能不是最佳方式,有没有其他方法可以实现这一目标?

1 个答案:

答案 0 :(得分:3)

您似乎完全想要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