简体   繁体   中英

Query left join without all the right rows from B table

I have 2 tables, A and B. I need all columns from A + 1 column from B in my select. Unfortunately, B has multiples rows(all identicals) for 1 row in A on the join condition.

I tried but I can't isolate one row in A for one row in B with left join for example while keeping my select.

How can I do this query ? Query in ORACLE SQL

Thanks in advance.

This is a good use for outer apply . The structure of the query looks like this:

select a.*, b.col
from a outer apply
     (select top 1 b.col
      from b
      where b.? = a.?
     ) b;

Normally, you would only use top 1 with order by . In this case, it doesn't seem to make a difference which row you choose.

You can group by on all columns from A , and then use an aggregate (like max or min ) to pick any of the identical B values:

select  a.*
,       b.min_col1
from    TableA a
left join
        (
        select  a_id
        ,       min(col1) as min_col1
        from    TableB
        group by
                a_id
        ) b
on      b.a_id = a.id

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