mysql - 如何从 Mysql 中的分层数据中获取位置名称?

标签 mysql sql

我有这样的表 Location:

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

如何在 MySQL 中创建一个返回此 View 的 View :

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

最佳答案

您可以使用连接或变量来做到这一点。但是, View 中不允许使用变量。所以,像这样:

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 ;

关于mysql - 如何从 Mysql 中的分层数据中获取位置名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27284399/

相关文章:

python - ImportError : this is MySQLdb version (1, 2, 4, 'beta' , 4), 但_mysql 是版本 (1, 2, 5, 'final' , 1)

php - 在 SELECT 语句中的单词左右添加空格

sql - 从 postgresql 中的数组中选择以获得所有可能的结果

MySQL简单查询错误

mysql - 如何合并这两个mysql表?

MySQL where JOIN 中的条件返回太多行

jquery - 创建了动态表单,但是如何进行查询呢?

mysql - 如何保持数据库中某些实体的更新(差异)

c# - 删除具有特定列的最高值的行

Mysql SUM 基于条件