简体   繁体   中英

How to join a same table with two tables?

I want to create an Oracle database view :

create or replace force view view_ind_pta (indi_code, nat_indi_code, indi_unite, indi_symbole, indi_lib, indi_cible, pta_intitule, indi_resp, 
indi_source_info, user_code, peri_mes_code, peri_mes_lib, pta_parent, deleted,obj_intitule,pta_action) 
as 
select distinct
i.indi_code,
i.nat_indi_code,
i.indi_unite,
i.indi_symbole,
to_char(i.indi_lib) as indi_lib,
i.indi_cible,
concat(concat(to_char(a.pta_ref),' - '),to_char(a.pta_intitule)) as pta_intitule,
i.indi_resp,
to_char(i.indi_source_info) as indi_source_info,
u.user_code,
i.peri_mes_code , 
pm.peri_mes_lib ,
concat(concat(to_char(p.pta_ref),' - '),to_char(p.pta_intitule)) as pta_parent,
i.deleted ,
to_char(o.obj_intitule) as obj_intitule,
concat(concat(to_char(action.pta_ref),' - '),to_char(action.pta_intitule)) as pta_action
from
indicateur i
left join acteur_saisie_indicateur ai on ai.indi_code = i.indi_code
left join acteur_verif_indicateur avi on avi.indi_code = i.indi_code
left join utilisateur u on ( ai.user_code = u.user_code and avi.user_code = u.user_code) 
left join objectif o on i.obj_code = o.obj_code
left join pta a on o.pta_code = a.pta_code
left join pta action on a.pta_pta_code = action.pta_code
left join pta p on action.pta_pta_code = p.pta_code 
left join periodicite_mesure pm on pm.peri_mes_code = i.peri_mes_code
where p.pta_definitif = 3;

In the view there is the table utilisateur which I want to join with the two tables acteur_saisie_indicateur and acteur_verif_indicateur . I tried the and operator , but I think it is not a good idea because the query will return rows only when there are joined rows in both tables ! Although this is not necessary : I want the query to return rows even if only one table has joined rows. So how to join these three tables ?

You need to join the table twice:

left join acteur_saisie_indicateur ai on ai.indi_code = i.indi_code
left join acteur_verif_indicateur avi on avi.indi_code = i.indi_code
left join utilisateur u on ai.user_code = u.user_code 
left join utilisateur u2 on avi.user_code = u2.user_code

We can include the same table in a FROM clause more than once. All we need to do is use different aliases to distinguish the instances:

left join utilisateur uai 
    on ai.user_code = uai.user_code
left join utilisateur uavi 
    on avi.user_code = uavi.user_code

The other thing you need to do is handle table's columns in the view's projection. You want to display the utilisateur values regardless of which instance the values come from, say by using nvl() or the industry standard coalesce()

coalesce(uai.user_code, uavi.user_code) as user_code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM