我的分层数据如下:
+------------+--------------+------------+----------+
| locationId | locationType | name | parentId |
+------------+--------------+------------+----------+
| 0 | country | U.S. | 0 |
| 1 | state | California | 0 |
| 2 | county | Los Angeles| 1 |
| 3 | county | Orange | 1 |
| 4 | city | Irvine | 3 |
| 5 | city | Newport | 3 |
| 6 | city | Pomona | 2 |
| 7 | city | Pasadena | 2 |
| 8 | zipCode | 92612 | 4 |
| 9 | zipCode | 92658 | 5 |
+------------+--------------+------------+----------+
我在这里只展示了一个数据样本。我想为每个位置选择它的某个级别的祖先(即国家、州或城市——当然州不能有县级祖先,所以不需要输出州行)。我怎样才能做到这一点?
例如,如果我想在县级输出数据,输出将是:
+------------+--------------+------------+----------------+
| locationId | locationType | name | countyParentId |
+------------+--------------+------------+----------------+
| 2 | county | Los Angeles| 2 |
| 3 | county | Orange | 3 |
| 4 | city | Irvine | 3 |
| 5 | city | Newport | 3 |
| 6 | city | Pomona | 2 |
| 7 | city | Pasadena | 2 |
| 8 | zipCode | 92612 | 3 |
| 9 | zipCode | 92658 | 3 |
+------------+--------------+------------+----------------+
PS 一个简化的因素是 ids 是按级别分配的,即 ids 从 0 开始并按递增顺序分配,直到用尽所有国家,然后是州,然后是城市等。