sql-server - 在 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 的零售价
解决方案
在选择的开头附近添加 3 列
d.InventoryItemID,
d.CatalogID,
e.CatalogID
然后从 Where 中删除 And ISNULL,然后运行看看你得到了什么。
可能是这样
join InventoryCatalog e
needs
ON d.CatalogID=ISNULL(e.catalogID,1)
推荐阅读
- kubernetes - 应该允许每个节点启动 30 个 pod
- loopbackjs - Loopback:发送额外的键/值对作为响应
- c# - 如何将 c# asp-format 标记中的小数格式化为 2 个小数点,如果它是 int,则不使用尾随零?
- python - 如何使用字典将多个值作为一个键
- entity-framework - Identityserver 4 Combined_AspNetIdentity_and_EntityFrameworkStorage
- r - 尝试在小于二维的对象上设置“colnames”时出错
- go - 等到满足条件或超时
- python - 无法解压不可迭代的对象/遍历python中的对象数组
- java - 返回类子类型的Java方法(不是实例,类本身)
- reactjs - React 如何在本地指定动画@keyframes 和类