oracle在left join时两表关联的字段为null时失效问题

问题描述

TESTA

subjectscore
语文90
数学30
英语9
100

TESTB

subjectscore
语文3
数学79
英语99
120

如果用left join会丢失掉TESTB的空值对应的120这个值

SELECT a.*, b.* 
FROM TESTA a
LEFT JOIN TESTB b ON a.subject = b.SUBJECT;
SUBJECTSCORESUBJECTSCORE
语文90语文3
数学30数学79
英语9英语99
100
解决方案

在left join前要将空数据赋值,

with a as (SELECT nvl(subject, '-')subject, score FROM TESTA ),
b as (SELECT nvl(subject, '-')subject, score FROM TESTB )
SELECT a.*, b.* 
FROM a
LEFT JOIN b ON a.subject = b.SUBJECT;
SUBJECTSCORESUBJECTSCORE
语文90语文3
数学30数学79
英语9英语99
-100-120

AllenYang
4 声望3 粉丝

We don't get to choose who we love