我有这样的表Location
:
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
答案 0 :(得分: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 ;