T-SQL WHERE NOT EXISTS - 结果不一致

时间:2018-06-05 13:37:17

标签: sql sql-server tsql not-exists

我有一个问题,哪些订单有od。[Bin Code] =' HISS'即使包含NOT EXISTS的查询在大多数时间都有效,也会被选中。有人可以解释这些订单有时只被选中吗?我们如何解决它?

SELECT *
FROM   [NAV2009].[dbo].[company\$sales line] AS line 
       JOIN [NAV2009].[dbo].[company\$sales header] AS Header 
         ON line.[document no_] = Header.no_ 
WHERE  NOT EXISTS (SELECT * 
                   FROM   [NAV2009].[dbo].[company\$sales line] od 
                   WHERE  line.[document no_] = od.[document no_] 
                          AND od.[bin code] = 'HISS') 
       AND Header.[website code] = 'DEFAULT' 
       AND [general comments] <> 'Picking' 

3 个答案:

答案 0 :(得分:1)

一种可能性是并非所有'HISS'都相同。也许空间是罪魁祸首。您可以尝试查询,例如:

select od.[Bin Code]
from [NAV2009].[dbo].[company\$sales line] od 
where od.[Bin Code] like '%H%I%S%S%' and
      od.[Bin Code] <> 'HISS';

一旦你理解了罪魁祸首,你就可以考虑如何解决这个问题。

答案 1 :(得分:0)

我可能在这里错了,特别是没有样本数据,我们可以看到OP的屏幕,但这可以在没有WHERE NOT EXISTS的情况下重写

FROM [NAV2009].[dbo].[Company\$Sales Line] AS line
INNER JOIN [NAV2009].[dbo].[company\$Sales Header] AS Header 
        ON  line.[Document No_] = Header.No_
    --to exclude rows where od.[Bin Code] <> 'HISS' then include in JOIN
        AND od.[Bin Code] <> 'HISS'
WHERE Header.[Website Code] <> 'DEFAULT'
AND [General Comments] = 'Picking'

答案 2 :(得分:0)

如果你看一下varbinary,你可能会看到差异

SELECT 'HISS', CAST('HISS' AS VARBINARY(4))