sql-server - 当辅助表在左连接中返回空值时从主表获取记录
问题描述
我有两个表(使用左外连接连接)主表总是有数据,辅助表可能有或很多没有使用 where 子句的数据,
我的问题是,当辅助表返回行时,如果辅助表返回零行,则只有我的查询显示一些数据,然后我的查询也返回零行,但据我所知,尽管辅助表返回零行,但我使用左连接我需要数据从主表。
select * from
(
SELECT Flag, [Description1], [group_code], [category_code]
FROM Item_TMP
) b --Primary table
Left outer join
Base a --Seconday table
on a.Part_ID = b.category_code
where b.category_code between 'A' and 'F'
AND b.type = 'Goods'
无论表 2 返回行如何,我都需要数据。
编辑
Item_TMP 表
Flag [Description1] [group_code] [category_code]
WO Computers FP A
SO LAptops FP F
基表
part_id quantity
A 50
F 100
现在基表可能会返回或可能不会返回
所需输出
如果基表返回数据,则
Flag [Description1] [group_code] [category_code] Sales
WO Computers FP A 50
SO LAptops FP F 100
如果基表不返回数据
Flag [Description1] [group_code] [category_code] Sales
WO Computers FP A 0
SO LAptops FP F 0
解决方案
您可以尝试使用ISNULL
或coalesce
功能
select b.*,coalesce(quantity,0) Sales
from
(
SELECT Flag, [Description1], [group_code], [category_code]
FROM Item_TMP
) b --Primary table
Left join
Base a --Seconday table
on a.Part_ID = b.category_code
where b.category_code between 'A' and 'F'
AND b.type = 'Goods'
推荐阅读
- sql - MS Access 日期比较中未包含年份
- javascript - 街景在加载时提供带有导航按钮的黑框,没有街道图像
- elasticsearch - ELK 和 LDAP 之间的集成
- nginx - Nginx 位置未解析
- powershell - 如何将交换属性同步到本地 AD 对象
- javascript - 如何在 for 循环中映射
- vb.net - 有没有办法避免在 VB 中重复使用公共共享变量?
- php - 如果值存在或等于其中的数组,则禁用按钮 while
- c# - Microsoft.AspNetCore.Authorization.DefaultAuthorizationService - 授权失败
- django - 在 Django Admin 中注册多个模型并排除公共字段