0

以下查询的行为有些奇怪:

SELECT #batches.OutTo, PO_Number, CONVERT(varbinary, #batches.OutTo) , convert     (varbinary, PO_Number), 
    CASE WHEN convert(varbinary, #batches.OutTo) NOT IN (SELECT convert(varbinary,    PO_Number) FROM #pos) 
         THEN 'NOT IN' ELSE 'IN' END
FROM #batches LEFT JOIN #pos ON 
    convert(varbinary, #batches.OutTo) = CONVERT(varbinary, PO_Number)
WHERE #batches.OutTo IS NOT NULL
GROUP BY #batches.OutTo, #pos.PO_Number


OutTo       PO_Number   (No column name)    (No column name)    (No column name)
311117      NULL        0x333131313137      NULL                    IN
311130      311130      0x333131313330      0x333131313330          IN
311259      NULL        0x333131323539      NULL                    IN
L001934     L001934     0x4C303031393334    0x4C303031393334        IN
L001988     NULL        0x4C303031393838    NULL                    IN
L002002     NULL        0x4C303032303032    NULL                    IN

正如你所看到的,左连接行为正确,但 NOT IN 没有,返回 IN 的值应该是 NOT IN。为什么是这样?它是一个错误,还是我不知道的 SQL 的一个特性?

4

2 回答 2

3

试试这个(你不需要子查询):

SELECT #batches.OutTo, PO_Number, CONVERT(varbinary(35), #batches.OutTo) , 
    convert     (varbinary(35), PO_Number), 
    CASE WHEN convert(varbinary(35), PO_Number) IS NULL THEN 'NOT IN' 
         ELSE 'IN' END

FROM #batches 
LEFT JOIN #pos ON 
    convert(varbinary(35), #batches.OutTo) = CONVERT(varbinary(35), PO_Number)
WHERE #batches.OutTo IS NOT NULL
GROUP BY #batches.OutTo, #pos.PO_Number
于 2012-11-05T01:46:37.490 回答
1

您正在使用SELECT convert(varbinary, PO_Number) FROM #pos没有任何过滤条件的子查询,我认为这会导致附加值并使其返回,IN因为值可能存在于列表中。

要解决此问题,我认为您还需要在子查询中添加适当的 where 子句,例如:

   SELECT convert(varbinary,    PO_Number) FROM #pos 
                          WHERE #batches.OutTo IS NOT NULL
于 2012-11-05T01:44:50.140 回答