0

次の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

これを解決する方法を知っている人はいますか?敬具、ジョナタン

4

1 に答える 1

2

まず、実際には外側のステートメントt1を参照しません。句select内の別のエンティティを参照しています。fromたまたま、SQL サーバーには、この種の機能を具体的に許可する構文があります: クロス適用/外部適用です。あなたの状況でこれを使用するには、次のようなものが必要です(テーブルを再作成できないため、テストされていません):

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 に答える