现有关系表到邻接表

时间:2018-10-22 15:30:45

标签: sql database postgresql

我正在尝试从现有关系表( PostgreSQL )中创建父子关系(邻接列表)。

这是现有的关系样本数据

+---------+-----------+-----------+--------+------------+
| Country |   State   |   City    |  Zip   | Population |
+---------+-----------+-----------+--------+------------+
| India   | Karnataka | Bengaluru | 560098 |        100 |
| India   | Karnataka | Bengaluru | 560019 |         50 |
| India   | Karnataka | Bengaluru | 560067 |         50 |
| India   | Kerala    | Cochin    | 690513 |         70 |
| India   | Kerala    | Cochin    | 680213 |         30 |
| India   | Andhra    |           |        |         80 |
| India   | Kerala    | Kannur    |        |         20 |
+---------+-----------+-----------+--------+------------+

预期输出(邻接表)

+-----+-----+-----------+--------------+------------+
| cid | pid |   Name    | relationship | Population |
+-----+-----+-----------+--------------+------------+
|   1 |     | India     | Country      |        300 |
|   2 |   1 | Karnataka | State        |        100 |
|   3 |   2 | Bengaluru | City         |         50 |
|   4 |   3 | 560098    | Zip          |         25 |
|   5 |   1 | Karnataka | State        |        100 |
|   6 |   2 | Bengaluru | City         |         25 |
|   7 |   3 | 560019    | Zip          |         20 |
|   8 |   1 | Karnataka | State        |        100 |
|   9 |   2 | Bengaluru | City         |         25 |
|  10 |   3 | 560067    | Zip          |         40 |
|  11 |   1 | Kerala    | State        |        100 |
|  12 |   4 | Cochin    | City         |         50 |
|  13 |   5 | 690513    | Zip          |         20 |
|  14 |   1 | Kerala    | State        |        100 |
|  15 |   4 | Cochin    | City         |         70 |
|  16 |   5 | 680213    | Zip          |         30 |
|  17 |   1 | Andhra    | State        |        100 |
|  18 |   1 | Kerala    | State        |        100 |
|  19 |   4 | Kannur    | City         |         50 |
+-----+-----+-----------+--------------+------------+

在如何通过SQL将现有关系表数据转换为邻接表方面,请有人帮我。这样,我们就可以以层次结构格式显示数据。

0 个答案:

没有答案