通过加入父和子,在单个表中选择使用concat孩子的身份

时间:2017-11-09 14:24:15

标签: join psql

我有一个有3列的表位于

之下
+---------------------------------------+
| id  | name                | parent_id |
+---------------------------------------+
| -1  | /                   |           |
| 1   | Organization        | -1        |
| 2   | United States       |  1        |
| 3   | Business Analyst    |  1        |
| 4   | Human Resources     |  1        |
| 5   | Benefits Manager    |  4        |
| 6   | Metropolitan Plant  |  2        |
| 7   | Administration      |  6        |
+---------------------------------------+

我的查询就像这样

SELECT CONCAT(parent.name, '/', child.name) AS path 
 FROM table_name AS child INNER JOIN table_name AS parent 
 ON child.id = parent.parent_id

我期待输出如下。

/Organization
/Organization/United States
/Organization/Business Analyst
/Organization/Human Resources
/Organization/Human Resources/Benefits Manager
/Organization/United States/Metropolitan Plant
/Organization/United States/Metropolitan Plant/Administration

2 个答案:

答案 0 :(得分:0)

好的......可能有一种更优雅的方式来做到这一点......特别是使用do循环......但是考虑到什么,你可能需要做几个连接。最高等级是低吗?希望如此。这是一个想法,但它很麻烦,可能需要很多假脱机,具体取决于您的数据大小:

SELECT CONCAT(path2, '/', D.name) AS path3
FROM
(SELECT CONCAT(path1, '/', B.name) AS path2
FROM
(SELECT CONCAT(parent.name, '/', child.name) AS path1 
FROM table_name AS parent LEFT JOIN table_name AS child
ON child.id = parent.parent_id) AS A
LEFT JOIN TABLE_NAME AS B
ON A.id = B.parent_id) AS C
LEFT JOIN TABLE_NAME AS D
ON C.id = D.parent_id

以上代码最多只能达到3个级别。如果想到更好的东西,我会发布它。

答案 1 :(得分:0)

怀疑你应该在这里使用分层查询

WITH foo (id, parent_id, name, fullpath)
     AS (SELECT id,
                parent_id,
                name,
                '/' AS fullpath
           FROM table_name
          WHERE parent_id IS NULL
         UNION ALL
         SELECT m.id,
                m.parent_id,
                m.name,
                f.fullpath || m.name || '/' AS fullpath
           FROM foo f JOIN table_name m ON (m.parent_id = f.id)) 
SELECT fullpath  FROM foo  
WHERE id > 0

那将非常接近。