I have two tables containing peoples data, first name, last name etc.
The first table contains the data I want to select if it matches the stuff from the second table. The problem is the first table might have only an initial for the first name.
I have tried variations of the following query but I am missing something obviously. I don’t mind if “J Bloggs” and “Joe Bloggs” from table 1 both match “Joe Bloggs” from table 2 that’s fine.
SELECT t1.* , LEFT(t2.FIRST_NAME, 1) AS firstChar
FROM t1, t2
WHERE t1.surname = t2.LAST_NAME
AND t1.firstname = t2.FIRST_NAME
OR t1.firstname = t2.firstChar
GROUP BY t1.surname
You need to put
()around your secondWHEREcondition as in:However, the implicit join syntax is discouraged and deprecated. Instead, use
Since your condition is that the last name must match, and the first name must either match fully or match the first character, the first name conditions have to be grouped inside
().I have also replaced your
GROUP BYwithORDER BY, since you are not performing any group aggregate functions (SUM(), COUNT(), AVG()). MySQL doesn’t permit aliases in theWHEREclause, so I have replacedt2.firstCharwithLEFT(t2.firstChar, 1)as well.Finally, you may find a need to convert the case of all the names with
UPPER()orLOWER()on both sides of the join to be sure it matches where casing may be inconsistent.