SQL Server结果因COALESCE和OR而异

php*_*v76 0 sql-server-2008

以下查询生成不同的计数.在我看来,他们是完全相同的.

SELECT 
    COUNT(*)
FROM 
    item1 
RIGHT JOIN 
    (Item2 
INNER JOIN 
    item_master ON Item2.Number = item_master.number) AND (item1.itemId = Item2.itemId)
WHERE  
    COALESCE([Item2].[Amount], item1.Amount, [item_master].[amount], 0 ) > 0

SELECT 
    COUNT(*)
FROM 
    item1 
RIGHT JOIN 
    (Item2 
INNER JOIN 
    item_master ON Item2.Number = item_master.number) AND (item1.itemId = Item2.itemId)
WHERE  
    (Item2.Amount is not NULL and Item2.Amount > 0) OR
    (item1.Amount is not NULL and item1.Amount > 0) OR 
    (item_master.amount is not NULL and item_master.amount > 0)
Run Code Online (Sandbox Code Playgroud)

Rem*_*anu 5

他们是不同的.COALESCE([Item2].[Amount], item1.Amount, [item_master].[amount], 0 ) > 0如果三者的第一个非空值大于0,则为true.

如果存在大于0的任何非空值,则第二个条件为真.