简体   繁体   中英

query with left outer join in sql

I have an issue with the below query:

select main.courseid
    ,main.coursename
    ,main.catid
    ,main.catname
    ,main.need_dte
from (
    select t1.courseid
        ,t1.coursename
        ,t2.catid
        ,t2
        ,catname
        ,t2.need_dte
    from t1
        ,t2
    where t1.courseid = t2.courseid
        and t1.coursename = t2.coursename
    ) main
left outer join (
    select courseid
        ,coursename
        ,need_dte training_info
    ) ui on main.courseid = ui.courseid
    and main.coursename = ui.coursename
    and main.need_dte = ui.need_dte

I have the above scenario in which i am trying to do left outer join between the tables "main" and "training_info".

main table: a inner join between t1 and t2 to get the training and the category details.

training_info(ui): has training details without category details.

here i have few course details in "main" and "ui" tables in common. and i have few unique course records in "main" table not in "ui" table. so i am trying to extract both the unique and common records.

I am able to get the results for this join, but the issue is with the need_dte. the need_dte field is present in both tables.In the result if the records are from "main" table am able to get the need_dte field updated from the inner table t2. if the records are from "ui" table in the result, the need_dte is not being populated.

Is there any way using this join set up I need to get the need_dte for the result records from training_info table also if those records have a need_dte.

Thanks!

Is this what you want?

select t1.courseid, t1.coursename, t2.catid, t2.catname,
       coalesce(ti.need_dte, t2.need_dte ) as need_dte
from t1 join
     t2 
     on t1.courseid = t2.courseid and
        t1.coursename = t2.coursename left outer join
     training_info ti
     on t1.courseid = ti.courseid and
        t1.coursename = ti.coursename and
        t2.need_dte = ti.need_dte;

I find your query with the nested subqueries, multiple levels of naming, and archaic join syntax to be difficult to read. I think the above is what you are looking for. It returns need_dte from training_info , if present, and then from t2 .

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