内连接中的null不等于输出不同的结果

时间:2013-12-05 15:39:02

标签: sql postgresql inner-join

SELECT upper(unaccent(nome)), ouid, nome_dois, ouid_dois FROM clientes 
INNER JOIN dblink('dbname=XXXXX.org','select upper(unaccent(nome)), ouid 
FROM clientes') AS c(nome_dois varchar, ouid_dois varchar) 
ON nome = nome_dois;

 upper                           |                 ouid                 |            nome_dois            | ouid_dois 
---------------------------------+--------------------------------------+---------------------------------+-----------
 JOAO BAPTISTA                   | b9b1866a-3301-11e1-8cbb-82d9f077e206 | JOAO BAPTISTA                   | 
 OSVALDO DE ALMEIDA JOAO         | 1cd643ba-1bb5-11e2-a232-66341e648f0f | OSVALDO DE ALMEIDA JOAO         | 
 .........

SELECT upper(unaccent(nome)), ouid, nome_dois, ouid_dois FROM clientes 
INNER JOIN dblink('dbname=XXXXX.org','select upper(unaccent(nome)), ouid 
FROM clientes') AS c(nome_dois varchar, ouid_dois varchar) 
ON nome = nome_dois 
AND ouid::varchar != ouid_dois::varchar;

upper | ouid | nome_dois | ouid_dois 
-------+------+-----------+-----------
(0 rows)

我的问题是关于AND ouid::varchar != ouid_dois::varchar查询之间的唯一区别就是这个条件。但是如果ouid_dois为空,为什么xxxxxx != null不起作用?查询应该输出相同的内容。

这些条件都是正确的,对吧?

ouid      ouid_dois
xxxxxx != null

ouid      ouid_dois
xxxxxx != yyyyy

2 个答案:

答案 0 :(得分:1)

错误。第一个条件是始终 false。除了is NULL之外,与NULL的任何比较都会产生NULL值 - SQL将其解释为FALSE。

所以,以下都是假的:

NULL = NULL
NULL <> NULL
x = NULL
x <> NULL

答案 1 :(得分:1)

NULL != NULL返回false - 您需要调整WHERE子句:

SELECT upper(unaccent(nome)), ouid, nome_dois, ouid_dois FROM clientes 
INNER JOIN dblink('dbname=XXXXX.org','select upper(unaccent(nome)), ouid 
FROM clientes') AS c(nome_dois varchar, ouid_dois varchar) 
ON nome = nome_dois 
AND (ouid::varchar IS NULL
  OR ouid_dois::varchar IS NULL)
  OR ouid::varchar != ouid_dois::varchar)