我有 3 个表格,其中包含非常相似的信息。这些表是所有者、经理和员工。我试图从所有 3 个表中提取信息,同时仍然了解每条记录来自哪个表。我也不想重复。所有表都有一个 email_id,它与email
我要加入的表相关。
此外,email_id 很可能会存在于多个表中(即,电子邮件可能是所有者和管理员,甚至可能是所有 3 个)。
到目前为止,这是我所拥有的:
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
这个查询实际上工作得很好。它单独从表中删除重复项,但将它们保留在多个表中。我仍然无法知道每个表来自哪个表。我试图将查询修改为:
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
这不起作用,因为并非所有表都具有相同的列。如果我将所有字段添加到所有表(即SELECT e.email, 'yes' as owner, '' as manager, '' as employee
),则查询有效,但所有表似乎都具有相同的字段。不知道为什么。
最终,我希望返回的记录集中没有重复的电子邮件地址,并且每条记录都类似于email = 'email address', owner = 'yes/no', manager = 'yes/no', employee = 'yes/no'
.
关于如何做到这一点的任何想法?如果您需要更多信息,请发表评论。谢谢!