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

如何用SQL连接两张表,保留TableA全量数据及TableB无匹配日期记录?

解决方案

要同时保留表A的全部数据,以及表B中存在但表A无对应日期的记录,可以使用**全外连接(FULL OUTER JOIN)**实现,以下是具体SQL语句:

标准SQL写法

SELECT
    COALESCE(a.Id, b.Id) AS Id,
    a.DateA AS DateTableA,
    b.DateB AS DateTableB,
    COALESCE(b.Comment, a.Comment) AS Comment
FROM TableA a
FULL OUTER JOIN TableB b
    ON a.Id = b.Id 
    AND a.DateA = b.DateB
ORDER BY Id, COALESCE(a.DateA, b.DateB);

MySQL兼容写法(不支持FULL OUTER JOIN时)

SELECT
    a.Id,
    a.DateA AS DateTableA,
    b.DateB AS DateTableB,
    COALESCE(b.Comment, a.Comment) AS Comment
FROM TableA a
LEFT JOIN TableB b
    ON a.Id = b.Id 
    AND a.DateA = b.DateB

UNION

SELECT
    b.Id,
    a.DateA AS DateTableA,
    b.DateB AS DateTableB,
    b.Comment AS Comment
FROM TableB b
LEFT JOIN TableA a
    ON a.Id = b.Id 
    AND a.DateA = b.DateB
WHERE a.Id IS NULL
ORDER BY Id, COALESCE(DateTableA, DateTableB);

问题详情

表A

IdDateAComment
102/10/2022comm1
103/10/2022comm2
202/10/2022comm3
203/10/2022comm4
301/10/2022comm5
302/10/2022comm6
303/10/2022comm7

表B

IdDateBComment
102/10/2022comm1
104/10/2022comm10
103/10/2022comm2

需求目标

  • 展示表A的全部数据
  • 通过Id和日期字段关联表A与表B

问题说明

需要同时获取表B中存在但表A无对应日期的记录(例如示例中comment为"comm10"的记录),期望得到如下查询结果:

期望查询结果

IdDateTableADateTableBComment
102/10/202202/10/2022comm1
103/10/202203/10/2022comm2
1null04/10/2022comm10
202/10/202202/10/2022comm3
203/10/202203/10/2022comm4
301/10/202201/10/2022comm5
302/10/202202/10/2022comm6
303/10/202203/10/2022comm7

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:25:29