LEFT JOIN查询的where子句中的存储过程可能会获得NULL参数

时间:2018-01-29 15:26:37

标签: sql stored-procedures subquery firebird

我在Firebird 2.5中执行查询的情况很奇怪:

select ps.ProductId, p.Id, p.DefPurcUOMNr, p.IsStockFlag 
  from ProductSupplier ps left join 
    Product p on p.Id = ps.ProductId 
where 
  (select q.Qty from ProductQtyBMUToUOM$(p.Id, p.DefPurcUOMNr, 1) as q) > 0 

上面的查询工作正常,但如果添加p.IsStockFlag = 1然后p.Id,则存储的proc p.DefPurcUOMNr的{​​{1}}参数将为ProductQtyBMUToUOM$传递等于NULL的记录1}}。

p.IsStockFlag = 0

我想这是正确的行为但我无法找到它的良好描述。只有我的猜测基于这种观察。

提前全部谢谢。

2 个答案:

答案 0 :(得分:2)

当您使用left join时,第二条件的条件应该在on子句中:

select ps.ProductId, p.Id, p.DefPurcUOMNr, p.IsStockFlag 
from ProductSupplier ps left join 
     Product p
     on p.Id = ps.ProductId and p.IsStockFlag = 1
where (select q.Qty from ProductQtyBMUToUOM$(p.Id, p.DefPurcUOMNr, 1) as q) > 0 ;

你说where子句工作得很好,所以我离开了它。我倾向于将其移至on条款 - 或者甚至将其单独join

答案 1 :(得分:0)

我没有看到关于p.IsStockFlag的任何标准。你的意思是以下吗?

select ps.ProductId, p.Id, p.DefPurcUOMNr, p.IsStockFlag 
  from ProductSupplier ps left join 
    Product p on p.Id = ps.ProductId 
where 
  p.IsStockFlag>0 and
  (select q.Qty from ProductQtyBMUToUOM$(p.Id, p.DefPurcUOMNr, 1) as q) > 0