JOIN关联字段出现NULL值与空值
作者:互联网
JOIN关联字段出现NULL值与空值
目录数据准备
INSERT INTO A (ID,NAME) VALUES ('01','');
INSERT INTO A (ID,NAME) VALUES ('02',NULL);
INSERT INTO A (ID,NAME) VALUES ('03','C');
INSERT INTO A (ID,NAME) VALUES ('04','D');
INSERT INTO A (ID,NAME) VALUES ('05',NULL);
INSERT INTO B (ID,NAME) VALUES ('01','A');
INSERT INTO B (ID,NAME) VALUES ('02','B');
INSERT INTO B (ID,NAME) VALUES ('03',NULL);
INSERT INTO B (ID,NAME) VALUES ('04','');
INSERT INTO B (ID,NAME) VALUES ('05','');
A表结果
B表结果
1、单字段关联
SELECT A.ID,A.NAME,B.ID,B.NAME
FROM A
LEFT JOIN B
ON A.NAME = B.NAME
查询结果
如果A.NAME是NULL,不会关联到B表中NAME,意味着并未关联到B表NAME为NULL的部分,但查询结果会保留主表中B.NAME为NULL的部分
2、关联字段包裹上 COALESCE
SELECT A.ID,A.NAME,B.ID,B.NAME
FROM A
LEFT JOIN B
ON COALESCE(A.NAME,'') = COALESCE(B.NAME,'')
查询结果
这里的COALESCE关联,将NULL改为'',可以将所有NULL的字段关联上
3、添加关联条件 COALESCE(A.NAME,'') <>''
SELECT A.ID,A.NAME,B.ID,B.NAME
FROM A
LEFT JOIN B
ON A.NAME = B.NAME
AND COALESCE(A.NAME,'') <>''
查询结果
这里COALESCE限制条件,会使得用‘’的部分关联不上
标签:INSERT,JOIN,NAME,INTO,空值,VALUES,NULL,ID 来源: https://www.cnblogs.com/fylhd2013/p/16356628.html