我目前正在研究PostgreSQL,它有兩個數據表,LU(后勤單位)和Item。
一個項目在一個LU中,一個LU可以在另一個LU中。
Item (id integer, name string, Luid integer references LU.id)
LU (id integer, name string, parentLuId references LU.id (can be null)
如果沒有LU,則parentLuId可以為null。
我希望顯示包含特定項的所有LU,即使該項位于該LU的子項中。
此示例包含一組數據
LU(1,"A",NULL)
LU(2,"B",NULL)
LU(3,"C",NULL)
LU(4,"D",NULL)
LU(5,"E",1)
LU(6,"F",5)
Item(1,"baloon",6)
Item(2,"baloon",2)
Item(4,"pencil",4)
Item(5,"baloon",3)
Item(6,"baloon",2)
Item(7,"baloon",6)
選擇包含baloon的UL應顯示ABCEF,因為D不包含baloon。A和E包含一個baloon,因為它們是包含baloon的F的父對象。
我希望能夠應付無限數量的父母。
這是一個帶有祖先的遞歸查詢。即:
這里是DBFiddle演示