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

如何移除UNION子句,用LEFT JOIN查询空值与金额不匹配项?

问题描述

我有一段使用UNION子句的查询语句,它能返回LEFT JOIN产生的空值以及金额不匹配的记录,目前可正确返回3行结果。请问是否有不复杂的方法,移除UNION子句后仍能查询出空值与Amount列的不匹配项?

原查询代码

declare @table1 table
(
    Id int,
    Amount decimal(8,2)
)
declare @table2 table
(
    Id int,
    Amount decimal(8,2)
)

insert into @table1
select 1, 1.50 union
select 2, 2.50 union
select 3, 3.50 union
select 4, 4.50 union
select 5, 5.50 


insert into @table2
select 1, 1.50 union
select 2, 2.75 union
select 3, 3.50


select t1.id, t1.amount, t2.id, t2.amount
from 
@table1 t1 left join @table2 t2 on
t1.Id = t2.Id
where 
t2.id is null

union

select t1.id, t1.amount, t2.id, t2.amount
from 
@table1 t1 inner join @table2 t2 on
t1.Id = t2.Id
where 
t1.Amount <> t2.amount

原查询结果

id  amount  id  amount
2   2.50    2   2.75
4   4.50    NULL    NULL
5   5.50    NULL    NULL
解决方案

可以直接通过LEFT JOIN + 复合WHERE条件实现,无需使用UNION子句,代码更简洁且逻辑清晰:

declare @table1 table
(
    Id int,
    Amount decimal(8,2)
)
declare @table2 table
(
    Id int,
    Amount decimal(8,2)
)

insert into @table1
select 1, 1.50 union
select 2, 2.50 union
select 3, 3.50 union
select 4, 4.50 union
select 5, 5.50 


insert into @table2
select 1, 1.50 union
select 2, 2.75 union
select 3, 3.50

-- 优化后的查询
select t1.id, t1.amount, t2.id, t2.amount
from @table1 t1 
left join @table2 t2 on t1.Id = t2.Id
where t2.Id is null -- 匹配不到对应ID的记录
   or t1.Amount <> t2.Amount -- ID匹配但金额不一致的记录

逻辑说明

  • LEFT JOIN会保留@table1中的所有记录,同时关联@table2中ID匹配的记录;
  • WHERE条件同时筛选两种目标场景:
    1. t2.Id is null:@table1中存在但@table2中无对应ID的记录;
    2. t1.Amount <> t2.Amount:ID匹配但金额不相等的记录。

这段优化后的查询会返回与原UNION查询完全一致的结果,且执行效率通常更优(避免了UNION带来的重复数据扫描和去重操作)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:35:23