I am trying to query 3 mostly unrelated tables. The relation for all three is one column (an email address field). I have created a 'union all' and pulled in email from all 3 tables and then grouped at the end to make sure there are no duplicates (I have tried union too).
My problem is that it all works fine, but I need to know if each email address is 1, 0 or NULL on the first table. I have tried pulling in the column and then adding to '"" AS Col1' to the other tables (avoid error 1222, match up the columns). I can do this but the data from table 1 gets overwritten by 'nothing' from table2 and then again by nothing in table 3.
Here's the query:
SELECT * FROM (
SELECT email AS emails, COUNT(email) AS qty, '' AS custCountry, '' AS custID, '' AS cName, active AS newsletter
FROM newsletter
WHERE email != ''
GROUP BY email
UNION ALL
SELECT email AS emails, COUNT(email) AS qty, '' AS custCountry, '' AS custID, '' AS cName, '' AS newsletter
FROM orders
WHERE email != ''
GROUP BY email
UNION ALL
SELECT email AS emails, COUNT(email) AS qty, country AS custCountry, customerID AS custID, countries.name AS cName, '' AS newsletter
FROM customers
LEFT JOIN countries ON customers.country = countries.zoneID
WHERE email != ''
GROUP BY email
) AS newtable
GROUP BY emails
ORDER BY qty DESC
It works until I add the 'active' column, at which point it overwrites whatever was in the active column with nothing. I need the third table there as it pulls in location data that I need to retain. If I were to put the first table last it would give me 'active' but overwrite the location columns.
I'm no MySQL pro (take a look!) so any help greatly appreciated.