我有3個表,其中包含非常相似的信息。這些表格是業主,經理和員工。我試圖從所有3張表中提取信息,同時仍然瞭解每條記錄來自哪個表。我也不想重複。所有表格都有一個email_id,它與我加入的email
表相關。MySQL:從多個表中選擇字段來顯示記錄來自哪個表
另外,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'
。
有關如何完成此任何想法?如果您需要更多信息,請點評。謝謝!
可選地添加3列的結果的每個塊。即添加* is_owner,is_manager,is_employee *到*全部* 3選擇塊 – vogomatix
您甚至可以刪除括號! –
我實際上已經嘗試爲每個結果塊添加3列,並且它不能正常工作。你能舉一個這樣的例子嗎? – Chris