我有tbl_vdc
表,其中包含:
id,zone_id, district_id, vdc_id, details
在这里,每个区域都有不同的区域,每个区域都有不同的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
的每个区域添加一个vdc_details max(vdc_id)+1
。
所以,新表将是这样的:
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次数据,这是耗时且不符合逻辑的方法。
有没有办法使用查询动态添加?
答案 0 :(得分: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 演示