Combining three SQL queries into one

I got working code from three queries but I would like to combine them into one or two. Basically I am checking if a provided phone number exists in table contacts or leads as well as if it exists as a secondary number in customfieldsvalues (not all leads have a customfield value though). I am using a CRM system based on CodeIgniter.

What I want to do (non-correct/hypothetical query):

SELECT * FROM contacts OR leads WHERE phonenumber = replace(X, '-', '')
OR leads.id = customvaluefields.relid AND cfields.fieldid = 41 AND cfields.value = X

Tables

table : contacts
+-------+----------------+----------------+
|   id  |   firstname    |  phonenumber   |
+-------+----------------+----------------+
|   1   |      John      |   214-444-1234 |
|   2   |      Mary      |   555-111-1234 |
+-------+----------------+----------------+

table : leads
+-------+-----------+---------------------+
|   id  |   name    |     phonenumber     |
+-------+-----------+---------------------+
|   1   |   John    |   214-444-1234      |
|   2   |   Mary    |   555-111-1234      |
+-------+-----------+---------------------+

table : customvaluefields
+-------+-----------+-------------+-----------+
|   id  |   relid   |   fieldid   |   value   |
+-------+-----------+-------------+-----------+
|   1   |     1     |     41      | 222333444 |
|   2   |     1     |     20      | Management|
|   3   |     2     |     41      | 333444555 |
+-------+-----------+-------------+-----------+

Solution 1:

If I understand what you are trying to, maybe UNION ALL would work. This is something to get you started:

SELECT C.ID, C.FirstName, C.Phonenumber 
FROM Contacts C 
JOIN CustomValueField CVF 
ON c.ID = CVF.RelID AND 
    CVF.ID = 41
    AND REPLACE(Phonenumber,'-','') = cvf.Value 
UNION ALL 
    SELECT L.ID, L.FirstName, L.Phonenumber 
FROM Leads L
JOIN CustomValueField CVF 
ON L.ID = CVF.RelID AND 
    CVF.ID = 41
    AND REPLACE(Phonenumber,'-','') = cvf.Value 

I'm joining the contacts and leads tables to CustomeValueField in each query and then UNION them together along with the WHERE clause in each. I'm sure it's not 100% correct for what you need, but should get you headed to a solution. Here is more information: https://dev.mysql.com/doc/refman/8.0/en/union.html