首页 > 解决方案 > 在 where 语句中为 null 不返回我的行

问题描述

我正在使用一个复杂的查询。即使它没有找到任何东西,我也需要总是给我返回一行。

SELECT 
  a.InventoryItemID,
  a.Name,
  a.RetailPrice,
  b.MainGroupItemCode,
  b.MainGroupItemID,
  c.VatValue,
  a.Code,
  a.Weight,
  b.MainGroupItemName,
  a.RetailPrice2,
  a.FreePrice,
  case when isnull(e.IsActive,0)=1 and isnull(d.price,0)!=0 then d.Price else RetailPrice End  as CustomPrice 
from InventoryMaster a 
join InventoryMainGroupItems b on a.MainGroupItemID=b.MainGroupItemID 
join VatCodes c on b.VatCodeID=c.VatCodeID 
join InventoryPrices d on d.InventoryItemID=a.InventoryItemID 
join InventoryCatalog e on e.CatalogID=d.CatalogID 
where a.InventoryItemID=2 and ISNULL(e.catalogID,1)=3

问题出在最后一行 ISNULL(e.catalogID,1)=3。在我的表中,它不存在编号为 3 的 CatalogID。因此它不会返回任何内容,但有编号为 1 的 CatalogID。我已将 if 设置为 null 以返回 1,不幸的是,我没有从查询中返回任何行. 我怎样才能解决这个问题 ?

我的问题已经解决了,我只想再添加一个连接表,其中包含一个条件

SELECT * 
from 
( 
SELECT t1.ID, 
t1.Name, 

COALESCE(t2.price,t1.Price) AS price , 
Row_number() OVER(partition BY t1.ID ORDER BY t1.ID) rn 
FROM InventoryMaster t1 
LEFT JOIN inventoryprices t2 
ON t1.ID=t2.ID 

LEFT join InventoryCatalog t3 
ON t3.ID=t2.ID and t3.ID=2 

where t1.ID=2 
) t 
WHERE t.rn=1

它总是返回我来自 First Table Inventory 的零售价

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

解决方案


在选择的开头附近添加 3 列

  d.InventoryItemID,
  d.CatalogID,
  e.CatalogID

然后从 Where 中删除 And ISNULL,然后运行看看你得到了什么。

可能是这样

join InventoryCatalog e
needs 
ON d.CatalogID=ISNULL(e.catalogID,1)

推荐阅读