I have 3 tables which contain very similar information. The tables are owners, managers, and employees. I am trying to pull information from all 3 tables, while still understanding which table each record came from. I also do not want duplicates. All tables have an email_id which relates to an email
table which I am joining.
Also, it is very likely that the email_id will exist in multiple tables (i.e. An email could be an owner and manager, or all 3 even).
Here is what I have thus far:
SELECT email
FROM (
(
SELECT e.email
FROM `owners` as o
LEFT JOIN `email` as e
ON e.email_id = o.email_id
WHERE o.company_id = 3
GROUP BY e.email
)
UNION ALL
(
SELECT e.email
FROM `managers` as m
LEFT JOIN `email` as e
ON e.email_id = m.email_id
WHERE m.company_id = 3
GROUP BY e.email
)
UNION ALL
(
SELECT e.email
FROM `employees` as emp
LEFT JOIN `email` as e
ON e.email_id = emp.email_id
WHERE v.company_id = 3
GROUP BY e.email
)
) as `people`
ORDER BY email ASC
This query actually works perfectly. It removes duplicates from the tables individually, but keeps them across multiple tables. I still have no way to know which table each comes from. I tried to modify the query to this:
SELECT email, owner, manager, employee
FROM (
(
SELECT e.email, 'yes' as owner
FROM `owners` as o
LEFT JOIN `email` as e
ON e.email_id = o.email_id
WHERE o.company_id = 3
GROUP BY e.email
)
UNION ALL
(
SELECT e.email, 'yes' as manager
FROM `managers` as m
LEFT JOIN `email` as e
ON e.email_id = m.email_id
WHERE m.company_id = 3
GROUP BY e.email
)
UNION ALL
(
SELECT e.email, 'yes' as employee
FROM `employees` as emp
LEFT JOIN `email` as e
ON e.email_id = emp.email_id
WHERE v.company_id = 3
GROUP BY e.email
)
) as `people`
ORDER BY email ASC
This did not work because not all tables had the same columns. If I add all fields to all tables (i.e. SELECT e.email, 'yes' as owner, '' as manager, '' as employee
) the query works, but all tables seem to have the same field. Not sure why.
Ultimately, I would like to have no duplicate email addresses in the returned record set, and have each record something like email = 'email address', owner = 'yes/no', manager = 'yes/no', employee = 'yes/no'
.
Any ideas on how to accomplish this? If you need further information, just comment. Thanks!