2014-12-04 68 views
0

我有表Location這樣的:如何從Mysql中的分層數據獲取位置名稱?

ID, PID, Location 
1 NuLL Country 
2 1  City 
3 2  County 
4 3  District 
5 4  Social 

如何使MySQL中的觀點,即返回此:

ID, Location, Full Location 
1  Country  Country 
2  City  City-Country 
3  County  County-City-Country 
4  District District-County-City-Country 
5  Social  Social-District-County-City-Country 

回答

3

您可以加入或變量做到這一點。但是,視圖中不允許使用變量。所以,這樣的事情:

select concat_ws('-', l.location, l1.location, l2.location, l3.location, l4.location) 
from location l left join 
    location l1 
    on l1.pid = l.id left join 
    location l2 
    on l2.pid = l1.id left join 
    location l3 
    on l3.pid = l2.id left join 
    location l4 
    on l4.pid = l3.id ; 
+0

這是很好用,當我知道有多少孩子的水平。但是如果我不知道孩子會有多少人,我該怎麼辦? – gianglaodai 2014-12-04 01:02:55

+1

@gianglaodai。 。 。 MySQL對分層查詢的支持可憐。您可以使用存儲過程(使用'while'循環)生成新表。但是你不能爲這種類型的查詢創建一個視圖。 – 2014-12-04 01:06:30

+0

關於數據庫我的水平是可怕的。你能告訴我怎麼做,數據庫如何工作? – gianglaodai 2014-12-04 01:23:00