0

我有tbl_vdc表,其中包含:

id,zone_id, district_id, vdc_id, details

在这里,每个zone有不同的区,每个区有不同的vdc。

zone_id |  district_id | vdc_id | details
1       |  1           | 1      | pyro   
1       |  1           | 2      | cuit  
1       |  1           | 3      | aden  

1       |  2           | 1      | rtyo   
1       |  2           | 2      | cyan 


2       |  1           | 1      | lity   
2       |  1           | 2      | pais  
2       |  1           | 3      | yeno  
2       |  1           | 4      | zige 


14       |  75           | 1      | moie   
14       |  75           | 2      | hode  
14       |  75           | 3      | gano  

等等多达14个区和75个区。

我需要N/A为每个vdc_id必须max(vdc_id)+1为该地区的地区添加一个 vdc_details。因此,新表将如下所示:

zone_id |  district_id | vdc_id | details

1       |  1           | 1      | pyro   
1       |  1           | 2      | cuit  
1       |  1           | 3      | aden   
1       |  1           | 4      | NA 

1       |  2           | 1      | rtyo   
1       |  2           | 2      | cyan 
1       |  2           | 3      | NA 


2       |  1           | 1      | lity   
2       |  1           | 2      | pais  
2       |  1           | 3      | yeno  
2       |  1           | 4      | zige 
2       |  1           | 5      | NA 

14       |  75           | 1      | moie   
14       |  75           | 2      | hode  
14       |  75           | 3      | gano 
14       |  75           | 4      | NA 

对于 14 个区和 75 个区,我需要添加 75 次数据,这是一种耗时且不合逻辑的方法。

有没有办法使用查询动态添加?

4

1 回答 1

2

尝试

INSERT INTO tbl_vdc (zone_id, district_id, vdc_id, details)
SELECT zone_id,
       district_id,
       MAX(vdc_id) + 1,
       'N/A'
  FROM tbl_vdc
 GROUP BY zone_id, district_id

样本输出:

| ID | ZONE_ID | DISTRICT_ID | VDC_ID | DETAILS |
-------------------------------------------------
|  1 |       1 |           1 |      1 |    pyro |
|  2 |       1 |           1 |      2 |    cuit |
|  3 |       1 |           1 |      3 |    aden |
| 13 |       1 |           1 |      4 |     N/A |
|  4 |       1 |           2 |      1 |    rtyo |
|  5 |       1 |           2 |      2 |    cyan |
| 14 |       1 |           2 |      3 |     N/A |
|  6 |       2 |           1 |      1 |    lity |
|  7 |       2 |           1 |      2 |    pais |
|  8 |       2 |           1 |      3 |    yeno |
|  9 |       2 |           1 |      4 |    zige |
| 15 |       2 |           1 |      5 |     N/A |
| 10 |      14 |          75 |      1 |    moie |
| 11 |      14 |          75 |      2 |    hode |
| 12 |      14 |          75 |      3 |    gano |
| 16 |      14 |          75 |      4 |     N/A |

这是SQLFiddle演示

于 2013-05-30T06:04:54.640 回答