1、使用left join时从表的过滤
WITH a AS(
SELECT 'A' aid FROM dual
UNION ALL
SELECT 'B' FROM dual
UNION ALL
SELECT 'C' FROM dual
UNION ALL
SELECT 'D' FROM dual
UNION ALL
SELECT 'E' FROM dual
),
b AS(
SELECT 'A' aid,10 num,1 type FROM dual
UNION ALL
SELECT 'B',20,2 FROM dual
UNION ALL
SELECT 'D',30,1 FROM dual
UNION ALL
SELECT 'E',10 ,1 FROM dual
)
SELECT t1.aid,NVL(t2.num,0) num,'0通过WHERE过滤' 备注
FROM a t1
LEFT JOIN b t2 ON t2.aid = t1.aid
WHERE t2.type = 1
UNION ALL
SELECT t1.aid,NVL(t2.num,0),'1通过JOIN条件过滤'
FROM a t1
LEFT JOIN b t2 ON t2.aid = t1.aid AND t2.type = 1
ORDER BY 3,1,2
结果如下:
2、使用(+)外连接时过滤从表
WITH a AS(
SELECT 'A' aid FROM dual
UNION ALL
SELECT 'B' FROM dual
UNION ALL
SELECT 'C' FROM dual
UNION ALL
SELECT 'D' FROM dual
UNION ALL
SELECT 'E' FROM dual
),
b AS(
SELECT 'A' aid,10 num,1 type FROM dual
UNION ALL
SELECT 'B',20,2 FROM dual
UNION ALL
SELECT 'D',30,1 FROM dual
UNION ALL
SELECT 'E',10 ,1 FROM dual
)
SELECT t1.aid,NVL(t2.num,0) num,'0不用外连接标识过滤'备注
FROM a t1,b t2
WHERE t2.aid(+) = t1.aid
AND t2.type = 1
UNION ALL
SELECT t1.aid,NVL(t2.num,0),'1使用外连接标识过滤'
FROM a t1,b t2
WHERE t2.aid(+) = t1.aid
AND t2.type(+) = 1
ORDER BY 3,1,2
结果如下