Skip to content
Advertisement

SQL If Not Any From Left Join Else Left Join

I the following query and I only want the results from the first left join that returns results for the addresses (add1/2/3). Is it possible, or should I just return it all and filer the results later?

select 
 -- if add1 has no results
 -- select add2
 -- if add2 has no results
 -- select add3
from names n, matter_counsel mc, counsel c
left join(
    FLUFF
) as add1 on X
left join(
    FLUFF
) as add2 on Y
left join(
    FLUFF
) as add3 on Z
where FLUFF

For example, if add1 returns 1 address, add2 returns 1 address and add3 returns 3 addresses, I only want the result set from add1.

Coalesce would give me incorrect results having record 1 from add1 and the other two results from add3.

Advertisement

Answer

Yes, it is possible. And its very rarely the better choice to filter results after the query, unless you hate yourself (or your data set is extremely small).

That being said, based on the information we have to work with, I would probably suggest you try a subquery to achieve the desired results. However, without additional information it may be impossible to answer exactly what changes you might need. As it is quite difficult to tell exactly what end results you are after.

As mentioned by @jarlh, you may want to look into reading the “How to create a Minimal, Complete, and Verifiable example” and post some data examples or explicitly state what you need.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement