首页 > 解决方案 > 当辅助表在左连接中返回空值时从主表获取记录

问题描述

我有两个表(使用左外连接连接)主表总是有数据,辅助表可能有或很多没有使用 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

标签: sql-serversql-server-2008sql-server-2005

解决方案


您可以尝试使用ISNULLcoalesce功能

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'

推荐阅读