嵌套选择并引用外表

时间:2013-05-13 14:49:43

标签: sql sql-server

我有以下sql语句。我从平面树结构中提取数据,我想选择匹配abos_daten.erstellt = (select MAX(erstellt)...

的单个关注者

问题是为了选择正确的MAX(erstellt)我需要以下条件where t2.parent_id = t1.parent_id。遗憾的是t1不能绑定,因为它引用了外部的select语句。它似乎创造了一个圆圈。

select * from trees as t1 inner join abos_daten as starter on t1.parent_id = starter.abonr 
right outer join 
  (select * from trees as t3 inner join abos_daten on t3.child_id = abos_daten.abonr 
   where  abos_daten.erstellt = (select MAX(erstellt) from abos_daten inner join trees as t2 on  t2.child_id = abos_daten.abonr
                                 where t2.parent_id = t1.parent_id and abos_daten.status_id <>  147
                                )
   ) as follower on t1.child_id = follower.abonr

有人知道如何解决这个问题吗?亲切的问候, 了Jonatan

1 个答案:

答案 0 :(得分:2)

首先,t1实际上并未引用外select语句;它引用from子句中的另一个实体。碰巧,SQL Server的语法特别允许这种功能:交叉应用/外部应用。要在你的情况下使用它,你需要这样的东西(未经测试,因为我无法重新创建你的表):

select * 
from trees as t1 
     inner join abos_daten as starter 
       on t1.parent_id = starter.abonr 
     outer apply (select MAX(erstellt) as max_erstellt
                  from abos_daten 
                       inner join trees as t2 
                         on  t2.child_id = abos_daten.abonr
                  where t2.parent_id = t1.parent_id 
                        and abos_daten.status_id <>  14) as t_m
     right outer join (select * 
                       from trees as t3 
                            inner join abos_daten 
                              on t3.child_id = abos_daten.abonr) as follower 
       on t1.child_id = follower.abonr 
          and t_m.max_erstellt = follower.erstellt