0

我有以下 sql 语句。我从一个扁平的树结构中提取数据,我想在其中选择一个匹配的追随者abos_daten.erstellt = (select MAX(erstellt)...

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

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

有谁知道如何解决这个问题?亲切的问候,乔纳坦

4

1 回答 1

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
于 2013-05-13T15:13:01.623 回答