You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并两表不同名称同类型列并关联获取对应字段?

解决方案

核心思路

使用UNION ALL合并两个表时,必须保证两边查询的字段数量、顺序、数据类型完全匹配。对于某张表不存在的字段,直接用NULL填充即可,缺失的数据会自动返回NULL。

1. 包含work_week及table b其他字段的完整查询

假设table b需要展示的字段为other_field,替换成你的实际字段名即可:

SELECT 
    shift_start_dt,
    work_week,
    other_field
FROM (
    -- 从table a取数据,table b的字段补NULL
    SELECT DISTINCT
        shift_begin_datetime AS shift_start_dt,
        work_week,
        NULL AS other_field
    FROM [table a] -- 表名含空格需用方括号包裹,或改为table_a
    UNION ALL
    -- 从table b取数据,work_week补NULL
    SELECT DISTINCT
        shift_start_datetime AS shift_start_dt,
        NULL AS work_week,
        other_field
    FROM [table b]
) AS combined_data

2. 仅获取shift_start_dt和work_week的简化查询

如果只需要这两个字段,代码可以简化为:

SELECT 
    shift_start_dt,
    work_week
FROM (
    SELECT DISTINCT
        shift_begin_datetime AS shift_start_dt,
        work_week
    FROM [table a]
    UNION ALL
    SELECT DISTINCT
        shift_start_datetime AS shift_start_dt,
        NULL AS work_week
    FROM [table b]
) AS combined_data

关键说明

  • 你之前的代码只选取了shift_start_datetime,所以临时表无法带出work_week,必须在子查询中明确列出所有需要的字段
  • DISTINCT用于去重,如果你不需要去重,可以直接去掉
  • 缺失数据会自动返回NULL,比如table b没有work_week字段,对应位置就显示NULL;table a没有table b的字段同理

内容的提问来源于stack exchange,提问作者sheesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 19:05:27