我有两张桌子
汽车:包含有关汽车的层次结构数据
+-----+-------------+-----------+
| id | description | parent_id |
+-----+-------------+-----------+
| 1 | All cars | 1 |
| 30 | Toyota | 1 |
| 34 | Yaris | 30 |
| 65 | Yaris | 30 |
| 87 | Avensis | 30 |
| 45 | Avensis | 30 |
| 143 | Skoda | 1 |
| 199 | Octavia | 143 |
| 12 | Yeti | 143 |
+-----+-------------+-----------+
car_mapping:包含映射数据,其中重复的汽车(具有不同的 id)被映射到一个 id。
+--------+----------+--------+
| car_id | car_name | map_id |
+--------+----------+--------+
| 34 | Yaris | 1 |
| 65 | Yaris | 1 |
| 87 | Avensis | 2 |
| 45 | Avensis | 2 |
| 199 | Octavia | 3 |
| 12 | Yeti | 4 |
| 30 | Toyota | 5 |
| 143 | Skoda | 6 |
| 1 | All cars | 0 |
+--------+----------+--------+
现在,我们的想法是创建第三个表cars_new,它基于cars和car_mapping删除重复项并根据car_mapping表中的字段重新键入cars表中的层次结构。这是生成的cars_new:map_id
+--------+----------+---------------+
| map_id | car_name | parent_map_id |
+--------+----------+---------------+
| 0 | All | 0 |
| 1 | Yaris | 5 |
| 2 | Avensis | 5 |
| 3 | Octavia | 6 |
| 4 | Yeti | 6 |
| 5 | Toyota | 0 |
| 6 | Skoda | 0 |
+--------+----------+---------------+
这是这个问题的SQL Fiddle。任何想法如何重新设置这个层次结构?