2017-03-16 22 views
0

我有以下格式的表:分層家長子女關係。自己加入還是工會或兩者兼而有之?

sid sname  pid  pname ppid  pdetail 

1.1 ABC  1.1.1 UVW  1.1.1.1  XSXXSX.... 
1.1 ABC  1.1.1 UVW  1.1.1.2  VDSVS... 
1.1 ABC  1.1.2 DEF  1.1.2.1  DSVSDSD.. 
1.1 ABC  1.1.2 DEF  1.1.2.2  SVSDV... 
1.2 XYZ  1.2.1 LMN  1.2.1.1  DFSDSD.. 
1.2 XYZ  1.2.2 GGF  1.2.2.1  CDSSS... 

等等...

我需要得到的結果在下面的格式..

Id   Detail  Parentid  ppid  pdetail 
1.1   ABC    NULL  1.1.1.1  XSXXSX.. 
1.1.1  UVW    1.1  ..   ... 
1.1.1  UVW    1.1  ..   .. 
1.1.2  DEF    1.1  ..   .. 
1.1.2  DEF    1.1 
    1.2  LMN    NULL 
1.2.1  LMN    1.2 
1.2.2  GGF    1.2 

我沒有想法如何進行...任何幫助將是偉大的如何進一步進行?

回答

0

您不需要self join,因爲您想要的關於父級的所有信息都已可用。所有你需要做的是一個union

select * 
from (
      select pid as Id, pname as Detail, sid as ParentId, ppid, pdetail 
      from table 
      union all 
      select sid, sname, null, ppid, pdetail 
      from table 
     ) 
order by Id 
+0

哎,查詢在result..only訂貨方面工作的偉大似乎很少problem..i'm得到的結果按以下順序。 – goonernike

+0

我得到1.1.1 1.1.1 1.1.2 1.1.2第一,然後1.1 ...而它應該是另一種方式..任何解決方案呢? – goonernike

+0

試試這個:'通過rpad命令(Id,5,'.0')' –

相關問題