I've been trying to create a query using COALESCE with multiple forms of matching in order to join two tables -- but as far as I can tell, it hasn't been working.
Can somebody tell me what's wrong with this query?
SELECT *
FROM t1
LEFT JOIN t2 ON COALESCE(t1.id,t1.phone,t1.address) = COALESCE(t2.id,t2.phone,t2.address)
Something like that. The hope would be that the query would look to see if the unique IDs in t1
and t2
matched first, and if they didn't, it would move on to see if the phones matched, etc. It would be very helpful to attempt to match on multiple sets of criteria and to return the ones that matched any of the column and to only return the NULLs from t1
if the query couldn't find a match at all.
Edit:
By "not working," I meant that it seems like the ID matching works -- where it will return the data from t2
(and not NULLs) if the unique identifiers matched, but it doesn't move on to attempt to match on phone number or address line; this is obviously likely because the t1
table isn't returning any NULL values.
The definitions of the table is that t1
is a smaller subset of data that likely lives in the larger t2
table. Let's say that t1
is a table of about 100 people with only a few criteria: name, phone, address, id (though ID doesn't exist in every row) -- whereas t2
is a larger table of about 30,000 with much more criteria (name, phone, address, id, job, volunteer, email, notes, etc.) where I'm trying to find the 100 within the 30k.