简体   繁体   中英

Getting a field from a table that is not in the left outer join in the same query

I have 4 tables, 3 of which are joined, but I need to get a field from the forth table (Table_D). For the sake of simplicity lets say they are Tables A, B, C, D.

Select Distinct A.Field_1, B.Field_2, C.Field_3
From Table_A
Left outer join B on A.Field_z= B.Field_z
Left Outer Join C on A.Field_z= C.Field_z
where A.Field_z in (1111);

This seems to work but I need a field in Table_D that is only connected to Table_A through Table_C.

How can I add it to the join? or can I?

Thanks!

WB

Of course you can add it. You don't specify the logic, but something like this:

Select Distinct A.Field_1, B.Field_2, C.Field_3, D.??
From Table_A a Left outer join
     B
     on A.Field_z= B.Field_z Left Outer Join
     C
     on A.Field_z= C.Field_z Left Outer Join
     D
     on . . . 
where A.Field_z in (1111);

Just fill in the conditions that you want. You want a left join , because the condition between c and d would otherwise turn the outer join to c into an inner join.

如果我理解正确,我相信这会奏效:

Left Outer Join D on C.Field_z= D.Field_z

You can try this way. It will help i guess

Select Distinct A.Field_1, B.Field_2, C.Field_3, c.Field_4
From Table_A
Left outer join B on A.Field_z= B.Field_z
Left Outer Join  ( select C.field_3, d.Field_4, c.Field_z from c inner join d on c.field_z = d.field_z ) c on A.Field_z= C.Field_z
where A.Field_z in (1111);

The on clause has essentially all the features of the where clause. on clauses for any part of the join can refer to any attribute of any entity in the from clause, I suspect your confusion comes from thinking that you can only join subsequent entities to the first entity in the from clause. If Table_D is related to Table_A through Table_C , you might see a from / join / on construct like:

select a.thing, b.things, c.thang, d.stuff
from Table_A a
 left join Table_B b
  on a.id = b.a_id
 left join Table_C c
  on a.id = c.a_id
 left join Table D d
  on d.id = c.d_id
where
  a.this = b.that

Note that the word "outer" is implied in a left join, and is not necessary for syntactic completion.

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