MYSQL SELECT returns FK 字段上没有空值

MYSQL SELECT returns nothing on FK field with NULL values

我正在尝试使用外键创建某种带有数据库的树。所以,有一个例子:

CREATE TABLE tree (
   id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
   pid INT(11) UNSIGNED NULL DEFAULT NULL,
   title VARCHAR(255) NOT NULL,
   PRIMARY KEY (id),
   CONSTRAINT TheTree FOREIGN KEY (pid) REFERENCES tree (id) ON UPDATE NO ACTION ON DELETE CASCADE
) ENGINE=InnoDB;

#insert sample data with 2 root nodes and 2 subnodes
insert into tree (id, pid, title) values 
     (null, null, 'test title 1'), 
     (null, null, 'test title 2'), 
     (null, 1,    'test title 1-1'), 
     (null, 2,    'test title 2-1');


select * from tree where pid = null
# it returns nothing.

这里是 sqlFiddle 示例。 我只是不明白。为什么我无法获得具有 NULL 值的根节点?我该如何处理?

您必须使用 is null 而不是 = null:

select * from tree where pid is null