如何用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
| Id | DateA | Comment |
|---|---|---|
| 1 | 02/10/2022 | comm1 |
| 1 | 03/10/2022 | comm2 |
| 2 | 02/10/2022 | comm3 |
| 2 | 03/10/2022 | comm4 |
| 3 | 01/10/2022 | comm5 |
| 3 | 02/10/2022 | comm6 |
| 3 | 03/10/2022 | comm7 |
表B
| Id | DateB | Comment |
|---|---|---|
| 1 | 02/10/2022 | comm1 |
| 1 | 04/10/2022 | comm10 |
| 1 | 03/10/2022 | comm2 |
需求目标
- 展示表A的全部数据
- 通过Id和日期字段关联表A与表B
问题说明
需要同时获取表B中存在但表A无对应日期的记录(例如示例中comment为"comm10"的记录),期望得到如下查询结果:
期望查询结果
| Id | DateTableA | DateTableB | Comment |
|---|---|---|---|
| 1 | 02/10/2022 | 02/10/2022 | comm1 |
| 1 | 03/10/2022 | 03/10/2022 | comm2 |
| 1 | null | 04/10/2022 | comm10 |
| 2 | 02/10/2022 | 02/10/2022 | comm3 |
| 2 | 03/10/2022 | 03/10/2022 | comm4 |
| 3 | 01/10/2022 | 01/10/2022 | comm5 |
| 3 | 02/10/2022 | 02/10/2022 | comm6 |
| 3 | 03/10/2022 | 03/10/2022 | comm7 |
内容的提问来源于stack exchange,提问作者FanOfTesting
相关产品推荐
相关产品推荐

