2016-11-02 51 views
3

我有一個名爲placeTable的表,它共有三列:id,parent_id,name,它包括國家,州和城市表。SQL Server:在沒有UNION ALL的情況下將同一列3次放入1列ALL

城市的parent_ID是州的id,州的parent_ID是國家的id。

而我有另一個名爲cityList的表指定城市,其id與placeTable的ID相同。

我想要的只是選擇Table2 cityList中列出的城市,包括表1中的州和國家。例如下面的表2顯示了悉尼,所以我想獲得悉尼這個城市的id,parent_ID和名稱,以及其州新南威爾士州和其國家澳大利亞在表1。

  • 表1:placeTable
id parent_ID name 
------------------- 
1  0  Australia 
2  0  UK 
33  1  NSW 
34  1  Western Australia  
55 33  Sydney 
70 34  Perth 
  • 表2:cityList
id  name 
------------------- 
55  Sydney 

輸出我想:

id parent_ID name 
------------------- 
1  0  Australia 
33  1  NSW 
55 33  Sydney 

我可以通過以下但太長做讓我想要的結果,我想可能有其他可用的更聰明的方法:

Select distinct pt.id,pt.parent_id,pt.name 
from placeTable AS pt 
join cityList as cl on cl.id = pt.id 
UNION ALL 
Select distinct ly2.id,ly2.parent_id,ly2.name 
from placeTable AS pt 
join cityList as cl on cl.id = pt.id 
join placeTable AS ly2 on pt.parent_id = ly2.id 
UNION ALL 
Select distinct ly3.id,ly3.parent_id,ly3.name 
from placeTable AS pt 
join cityList as cl on cl.id = pt.id 
join placeTable AS ly2 on pt.parent_id = ly2.id 
join placeTable as ly3 on ly2.parent_id = ly3.id 

我在下面試過了,但是這隻能給我城市:

Select distinct pt.id,pt.parent_id,pt.name 
from placeTable AS pt 
join cityList as cl on cl.id = pt.id 
join placeTable AS ly2 on pt.parent_id = ly2.id 
join placeTable as ly3 on ly2.parent_id = ly3.id 
+0

我不確定要理解這個問題:您想遞歸查找表以打印完整的child-> parent層次結構? – Shastick

+0

我認爲你只需要在你的第一個SQL語句的SELECT列表中添加'ly2.name'和'ly3.name'就可以了。你加入這些表,但是你不選擇它們...'Select distinct bu.id,bu.parent_id,bu.name,ly2.name,ly3.name' – JNevill

+1

你的查詢沒有任何意義。什麼是'bu'? –

回答

2

請試試這個:

  create table #placeTable (ID int, ParentID int, Name varchar(20)) 
      insert into #placeTable (ID, ParentID, Name) 
      values (1,0,'Australia'), (2,0,'UK'), (33,1,'NSW'), (34,1,'Western Australia'), 
      (55,33,'Sydney'),(70,34,'Perth'); 

      create table #cityList (ID int, Name varchar(20)) 
      insert into #cityList (ID, Name) 
      values (55, 'Sydney'), (70, 'Perth'); 

      WITH Selects AS (
      SELECT p.*, c.ID as 'GroupID' 
      FROM #placeTable p 
      INNER JOIN #cityList c on p.ID = c.ID 

      UNION ALL 
      SELECT p.*, s.GroupID 
      FROM #placeTable p 
      INNER JOIN Selects s ON p.ID = s.ParentID 
      ) 
      SELECT ID, ParentID, Name FROM Selects ORDER BY GroupID, ID