2017-04-22 95 views
-1

我有一個下表。如何找到鏈接的數據?

chained_schedule

chained_id parent_schedule_id next_schedule_id 
    1    71     72 
    2    72     73 
    3    74     75 

當我給作爲輸入parent_schedule_id=71,輸出應該發現,特定的記錄,並通過其next_schedule_id鑑定的記錄,而這又可以鏈接到其他記錄,...等等。

因此,對於上述數據和查詢,輸出應該是這樣的:

chained_id parent_schedule_id next_schedule_id 
    1    71     72 
    2    72     73 

我怎樣才能做到這一點?

+0

什麼?請詳細說明你在做什麼 –

+2

你正在使用哪些DBMS? Postgres的?甲骨文? –

+0

如果您給parent_schedule_id = 71,則只應選擇第一行。爲什麼第2行有parent_schedule_id 72? –

回答

1

大多數數據庫都支持某種形式的遞歸CTE。 ANSI語法是:

with recursive cte as (
     select cs.* 
     from chained_schedule cs 
     where parent_schedule_id = 71 
     union all 
     select cs.* 
     from chained_schedule cs join 
      cte 
      on cte.next_schedule_id = cs.parent_schedule_id 
    ) 
select * 
from cte; 
+0

我們可以使用spring數據jpa來實現這個CTE嗎? –

+0

我不使用使用彈簧數據jpa。您可以在任何支持ANSI標準遞歸CTE(Postgres,Oracle,SQL Server,DB2,Teradata都可以想到)的數據庫中實現此功能。 –

+0

我試圖在oracle 11g中運行這個查詢,但是我在線路號錯誤。 1(缺少關鍵字) –

相關問題