我的分层数据如下:
+------------+--------------+------------+----------+
| 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 |
+------------+--------------+------------+----------------+
P.S。一个简化因素是ID是按级别分配的,即ID从0开始并按递增顺序分配,直到所有国家都用尽,然后是州,然后是城市等。