Restricting a LEFT JOIN

后端 未结 5 602
梦如初夏
梦如初夏 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:32
    1. add a where (main.col2 = a.col2)

    2. just do a join instead of a left join.

    0 讨论(0)
  • 2021-01-06 04:33
    SELECT ...
    FROM ....
    LEFT JOIN ( a INNER JOIN b ON .... ) ON ....
    
    0 讨论(0)
  • 2021-01-06 04:34
        Select ... 
        From Main 
         Left Join a on main.col2 = a.col2
        where a.col3 in (select b.col3 from b) or a.col3 is null
    

    you may also need to do some indexing on a.col3 and b.col3

    0 讨论(0)
  • 2021-01-06 04:54

    What if you created a view that gets you the "a" to "b" join, then do your left joins to that view?

    0 讨论(0)
  • 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. :-)

    0 讨论(0)
提交回复
热议问题