2016-02-27 93 views
2

我想寫一個類似於下面的查詢。複雜的SQL加入與前1條記錄的子查詢

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的列。 有沒有辦法做到這一點? 我知道這可能不是最理想的方式,還有其他方法可以實現嗎?

回答

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子句中,並且可以返回多列和多行。

注意:當您使用TOP時,您應該使用ORDER BY

+0

另外'APPLY'可以返回多個 –

+0

@MotoGP。 。 。當然。謝謝。 –

+0

在'Oracle','Postgres'或任何用於'APPLY'運算符的DBMS中是否有任何等價物。我真的很喜歡它的靈活功能 –