[英]How to keep null records in this left join?
即使fruit_batch_info中沒有記錄,我也希望結果中包含AP01,所以我使用的是左連接。
但是,一旦我添加“ where fruit_batch_info = 11”,則我的AP01將不再出現在結果中。
如何保持AP01的結果?
要求:報告“ all_fruits”中的所有記錄以及有關“ fruit_batch = 11”的任何信息
所需結果
ID , DESC , BATCH, STORAGE
----- -------- ------ ------------
APO1, Apple , null , null
PE01, Pear , 11 , Warehouse-11
KU01, Kumquat, 11 , Warehouse-11
這是我的查詢:
with all_fruits as
(select 'AP01' as fruit_id, 'Apple' as fruit_desc from dual union all
select 'PE01' as fruit_id, 'Pear' as fruit_desc from dual union all
select 'KU01' as fruit_id, 'Kumquat' as fruit_desc from dual),
fruit_batch_info as
(select 'PE01' as fruit_id, '10' as fruit_batch , 'Warehouse-10' as fruit_storage from dual union all
select 'PE01' as fruit_id, '11' as fruit_batch , 'Warehouse-11' as fruit_storage from dual union all
select 'PE01' as fruit_id, '12' as fruit_batch , 'Warehouse-12' as fruit_storage from dual union all
select 'KU01' as fruit_id, '10' as fruit_batch , 'Warehouse-10' as fruit_storage from dual union all
select 'KU01' as fruit_id, '11' as fruit_batch , 'Warehouse-10' as fruit_storage from dual)
select a.fruit_id ,
fruit_desc,
fruit_batch,
fruit_storage
from all_fruits a
left join fruit_batch_info i on a.fruit_id = i.fruit_id
where i.fruit_batch='11'
使用LEFT JOIN
,將該表中的條件添加到join ON
子句中,而不是WHERE
子句中:
left join fruit_batch_info i on a.fruit_id = i.fruit_id and i.fruit_batch='11'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.