基于表c的type条件向表s插数据:能否用单循环实现?
现有表结构及数据
表c
| id | type |
|---|---|
| 1 | B1 |
| 2 | B2 |
| 3 | B3 |
表s
| id | s_id | s_type |
|---|---|---|
| 1 | 2 | C1 |
| 2 | 2 | C2 |
| 3 | 3 | C2 |
问题解答
完全可以用一个循环实现需求,而且这么做很有意义。
优化后的单循环代码
for rec in ( select id, case type when 'B1' then 'C2' when 'B2' then 'C1' end as target_s_type from c where type in ('B1', 'B2') ) loop begin next_id = get_next_id('id_seq', next_id, 1000); insert into s(id, s_id, s_type) values (next_id, rec.id, rec.target_s_type); end; end loop;
为什么这么做有意义
- 减少代码冗余:避免重复编写几乎一致的循环逻辑,后续维护时只需修改一处即可调整映射规则或插入逻辑。
- 逻辑更清晰:所有
type到s_type的映射规则集中在查询的case语句里,一眼就能看懂整体的关联关系。 - 潜在性能提升:相比两次循环两次查询,单循环只需要扫描一次表
c的目标数据,减少了数据库的查询开销(具体效果取决于数据库优化器,但逻辑上更高效)。
另外补充:如果你的get_next_id函数支持批量生成唯一ID,还可以进一步去掉循环,直接用批量插入语句完成,效率会更高:
insert into s(id, s_id, s_type) select get_next_id('id_seq', next_id, 1000), id, case type when 'B1' then 'C2' when 'B2' then 'C1' end as target_s_type from c where type in ('B1', 'B2');
注:需确认get_next_id函数在批量场景下能否正确生成不重复的ID,若函数只能逐行调用生成,则单循环仍是最优选择。
内容的提问来源于stack exchange,提问作者SCM
相关产品推荐
相关产品推荐

