Restricting a LEFT JOIN

后端 未结 5 654
梦如初夏
梦如初夏 2021-01-06 03:59

I have a table, let\'s call it \"a\" that is used in a left join in a view that involves a lot of tables. However, I only want to return rows of \"a\" if they also join wit

5条回答
  •  一个人的身影
    2021-01-06 04:59

    First define your query between table "a" and "b" to make sure it is returning the rows you want:

    Select
       a.field1,
       a.field2,
       b.field3
    from
       table_a a
    
       JOIN table_b b
          on (b.someid = a.someid)
    

    then put that in as a sub-query of your main query:

    select
       m.field1,
       m.field2,
       m.field3,
       a.field1 as a_field1,
       b.field1 as b_field1
    from
       Table_main m
    
       LEFT OUTER JOIN
          (
          Select
             a.field1,
             a.field2,
             b.field3
          from
             table_a a
    
             JOIN table_b b
                on (b.someid = a.someid)
          ) sq
       on (sq.field1 = m.field1)
    

    that should do it.

    Ahh, missed the performance problem note - what I usually end up doing is putting the query from the view in a stored procedure, so I can generate the sub-queries to temp tables and put indexes on them. Suprisingly faster than you would expect. :-)

提交回复
热议问题