I'm trying to use MYSQL's INNER JOIN using two optional clauses. But it doesn't seem to be returning all the data. Any tips on how I can improve this query?
SELECT *
FROM ImportedContacts t1
INNER JOIN users t2
ON (t1.Emails = t2.email OR
t1.Phones = t2.Phone)
WHERE t1.Username = 'user' AND
NOT t2.email = ''
ORDER BY t2.first_name
LIMIT 60
EDITED
I changed the title from "MYSQL INNER JOIN with OR Clause" to the current one to make it easier to find for people having the same problem. It turns out this issue actually had to do with the columns being JOINED having empty or null values. The accepted answer explains the cause of the problem and provides a solution.
I found the solution. According to this article, INNER JOIN
won't work with fields that have NULL
or empty values. The Answer above didn't work since the CLAUSE that was meant to filter out the NULL
columns ran after the INNER JOIN
was evaluated with the NULL
or empty columns. So considering this information I filtered out the NULL
columns in the actual INNER JOIN
statement as opposed to after.
SELECT *
FROM importedcontacts
INNER JOIN users
ON ( users.email = importedcontacts.emails
OR ( ( importedcontacts.phones = users.phone )
AND NOT importedcontacts.phones = ''
AND NOT users.phone = '' ) )
WHERE importedcontacts.username = 'user'
ORDER BY users.first_name
And it worked! thanks for the help guys.