表与NULL值比较

时间:2016-01-14 23:22:38

标签: php mysql sql database compare

我正在寻找比较两个表的最佳方法,并返回包含两个表之间差异的行。

//表A

CREATE TABLE `mydb`.`a` (
  `id` int(10) unsigned NOT NULL,
  `color` varchar(45) DEFAULT NULL,
  `animal` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `mydb`.`a` 
    (id,color,animal) 
VALUES 
    (1,"red",""),
    (2,"blue","cat"),
    (3,"green","dog");
    (4,"orange","fish");

//表B

CREATE TABLE `mydb`.`b` (
  `id` int(10) unsigned NOT NULL,
  `color` varchar(45) DEFAULT NULL,
  `animal` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `mydb`.`b` 
    (id,color,animal) 
VALUES 
    (1,"red",""),
    (2,"blue","cat"),
    (3,"green","bird");
    (4,"brown","fish");

该语句将返回表B的第3,4行,因为birdbrowndogorange不同。

1 个答案:

答案 0 :(得分:2)

NULL表示缺少信息。它永远不会匹配其他值(包括其他NULL)。因此,例如,零等于零:

SQL> select case when 0 = 0 then 'true' else 'false' end ;
case when 0 = 0 then 'true' else 'false' end
--------------------------------------------
true                                    

NULL 等于NULL:

SQL> select case when null = null then 'true' else 'false' end ;
case when null = null then 'true' else 'false' end
--------------------------------------------------
false                             

如果你想匹配它们,你必须 NULL转换为其他值(例如零):

SQL> select case when ifnull(null, 0) = ifnull(null, 0) then 'true' else 'false' end ;
case when ifnull(null, 0) = ifnull(null, 0) then 'true' else 'false' end
------------------------------------------------------------------------
true   

修改

假设你有:

mysql> select * from a;
+----+--------+--------+
| id | color  | animal |
+----+--------+--------+
|  1 | red    |        |
|  2 | blue   | cat    |
|  3 | green  | dog    |
|  4 | orange | fish   |
+----+--------+--------+
4 rows in set (0.00 sec)

mysql> select * from b;
+----+-------+--------+
| id | color | animal |
+----+-------+--------+
|  1 | red   |        |
|  2 | blue  | cat    |
|  3 | green | bird   |
|  4 | brown | fish   |
+----+-------+--------+
4 rows in set (0.00 sec)

我会用:

mysql> select b.* from b left outer join a on a.id = b.id and 
       a.animal = b.animal and a.color = b.color 
       where a.id is null and a.animal is null and a.color is null ;
+----+-------+--------+
| id | color | animal |
+----+-------+--------+
|  3 | green | bird   |
|  4 | brown | fish   |
+----+-------+--------+
2 rows in set (0.00 sec)

查找B中的行,与A中的相应行有所不同。 和

mysql> select a.* from a left outer join b on a.id = b.id and 
       a.animal = b.animal and a.color = b.color 
       where b.id is null and b.animal is null and b.color is null ;
+----+--------+--------+
| id | color  | animal |
+----+--------+--------+
|  3 | green  | dog    |
|  4 | orange | fish   |
+----+--------+--------+
2 rows in set (0.00 sec)

查找A中与B中相应行不同的行。