2014-12-04 42 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