【问题标题】:Is null in where statement doesnt returns me rows在 where 语句中为 null 不返回我的行
【发布时间】:2019-02-09 22:01:35
【问题描述】:

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

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 返回我的零售价

【问题讨论】:

  • 我实际上不确定ISNULL(e.catalogID,1)=3 的目标是什么,如果catalogID 的值是NULL,那么它不是3(实际上NULL 不是等于NULL) 所以你可以用e.catalogID = 3 替换子句。但是,您在下面的段落中要说的话恐怕没有什么意义。也许这里有语言障碍;如果是这样,我建议您请更熟悉英语的人来翻译您的问题,因为它目前没有任何意义。
  • 您似乎是在说您没有任何 catalogID 值为 3 的行,所以我希望该查询永远不会返回任何行。这就像有一个子句 WHERE ID = -1 但列 ID 的所有值都是正数。
  • 我可以给一个远程桌面,想必你能更好地理解我的意思。
  • 恐怕我不是顾问(你必须为此付费)。
  • 没问题。

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


【解决方案1】:

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

  d.InventoryItemID,
  d.CatalogID,
  e.CatalogID

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

可能是这样的

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

【讨论】:

  • 我建议反对ISNULLWHERE/ON;它会使查询成为非 SARGable。改用正确的布尔逻辑/
  • 为什么这不起作用?其中 a.InventoryItemID=2 和 ISNULL(e.catalogID,1)=3
  • 多少行有 SELECT InventoryItemID, CatalogID FROM [InventoryPrices] where InventoryItemID = 2 and CatalogID = 1
猜你喜欢
  • 1970-01-01
  • 2011-09-07
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多