SQL如何按指定规则合并tbl1和tbl2且不覆盖原有列值
解决方案
你的需求是将tbl1和tbl2按要求合并,输出字段与tbl1结构对齐,两种实现方案如下:
方案1:FULL JOIN 方案(适合同id行需要合并字段的场景)
你原代码的问题有两处:
- 笔误:
coalesce(t1.id, t2.d)中的t2.d应为t2.id - 若你遇到coalesce优先取第二个参数的问题,是参数顺序写反导致的:coalesce会返回第一个非空的参数,把优先取值的字段写在前面即可
修正后的代码:
select coalesce(t1.id, t2.id) as id, t1.fname, t1.mname, t1.lname, coalesce(t1.age, t2.age) as age, coalesce(t1.addr, t2.addr) as addr, t1.email, t1.location from tbl1 t1 full join tbl2 t2 on t1.id = t2.id
方案2:UNION ALL 方案(适合两张表id无重叠,仅需拼接所有行的场景)
你的样例数据中两张表id无重叠,仅需把行拼接起来,用UNION ALL性能更高,逻辑更直观:
-- 取tbl1全量数据 select id, fname, mname, lname, age, addr, email, location from tbl1 union all -- 取tbl2数据,缺少的字段补null select id, null as fname, null as mname, null as lname, age, addr, null as email, null as location from tbl2
内容的提问来源于stack exchange,提问作者Byte
相关产品推荐
相关产品推荐

