2013-05-13 20 views
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 

有没有人知道如何解决这个问题?亲切的问候, jonatan

+0

像'abos_daten'表名称并没有多大的意义,以英语为母语。也许你可以编辑你的问题来包含表格和列名,这有助于阐明你的例子。 – Andomar 2013-05-13 14:53:23

回答

2

首先,t1实际上并不指select语句;它是指from子句中的另一个实体。碰巧,SQL服务器有一个特别允许这种功能的语法:cross apply/outer apply。要在您的情况使用,你会想是这样的(未经测试,因为我不能重新创建表):

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 
+0

到目前为止的正确的溶剂。我正在测试我的数据。谢谢! – encc 2013-05-14 14:51:20