i have the following two tables:
Table1
id name
---------
A3 B2
A3 B400
A5 B100
A7 B200
A8 B6
A8 B2
A8 B3
and
These requirements are confusing enough it might be worth a re-assessment of your data model. I think the UNION
solution is your best bet possibly modified to use UNION ALL
for efficiency.
I did put together a mutex based hack that likely has as many subtle problems as any of the other queries on this page.
select
coalesce(t2.id, t1.name) AS ID,
coalesce(t2.company, t1.name) AS Company,
if(isnull(t2.id), 'NOT FOUND', 'FOUND') as Status
from (select 0 as mutex union select 1) as m
left join table1 as t1 on 1 = 1
left join table2 as t2 on t1.name = t2.name or (t1.id = t2.id and mutex)
group by coalesce(t2.id, t1.name)
That said, please test these queries carefully and look over your data and results. There's a whole lot of room for error depending on your input data.