I have two tables:
Table A:
id name
------------
1 Scott
2 Dan
3 Sam
Table B:
id name
------------
1 Dan
2 Andi
3 Jess
My result needs to be:
Id Name Found
1 Scott A
2 Dan C i.e. found in both
3 Sam A
2 Andi B
3 Jess B
I am able to do a UNION to fetch the result but how do I create the Found column?
The way to do this is to use a FULL OUTER JOIN, but since this is not supported in MySQL you can instead use a combination of a LEFT JOIN and INNER JOIN and RIGHT JOIN.
In fact, you only need a LEFT and RIGHT JOIN because you can handle the INNER JOIN at the same time as you do one of the other two joins. I think the above demonstrates the principle more clearly, but in practice the following will give better performance:
Result: