Left Outer join and an additional where clause

前端 未结 5 985
南方客
南方客 2020-12-18 18:05

I have a join on two tables defined as a left outer join so that all records are returned from the left hand table even if they don\'t have a record in the right hand table.

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-18 18:23

    select * 
      from table1 t1 
      left outer join table2 t2 on t1.id = t2.id
     where t1.some_field = nvl(t2.some_field, t1.some_field) 
    

    UPD: errr... no. this way:

    select * 
      from table1 t1 
      left outer join table2 t2 on t1.id = t2.id
     where some_required_value = nvl(t2.some_field, some_required_value) 
    

    nvl is an Oracle syntax which replaces first argument with second in case it is null (which is common for outer joins). You can use ifnull or coalesce for other databases.

    Thus, you compare t2.some_field with your search criteria if it has met join predicate, but if it has not, then you just return row from table1, because some_required_value compared to itself will always be true (unless it is null, however - null = null yields null, neither true not false.

提交回复
热议问题