即使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'
答案 0 :(得分:5)
使用LEFT JOIN
时,将该表中的条件添加到联接ON
子句中,而不是WHERE
子句中:
left join fruit_batch_info i on a.fruit_id = i.fruit_id and i.fruit_batch='11'