2013-05-13 21 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