MySQL查询列出每个用户出现在多个表中的次数

时间:2018-10-25 21:57:43

标签: mysql list join ranking

我正在重新阐明我的问题。 我有几个(准确地说是5个)表,其中一个用户只能出现一次。我想列出每个用户出现多少次。

示例:

**employess table** 
email | cn | more columns.. user@gr.com | name | etc

**intranet table** 
email | data1 | more columns.. user@gr.com | something | etc
user1@gr.com | something | etc
user2@gr.com | something | etc

**sap table** 
email | data1 | more columns.. 
user@gr.com | something | etc
user1@gr.com | something | etc
user2@gr.com | something | etc

**solman table** 
email | data1 | more columns.. 
user@gr.com | something | etc
user1@gr.com | something | etc
user2@gr.com | something | etc

**orfeo table** 
email | data1 | more columns.. 
user@gr.com | something | etc
user3@gr.com | something | etc

**saul table** 
email | data1 | more columns.. 
user@gr.com | something | etc
user3@gr.com | something | etc

**EXPECTED RESULT**

   email      | Name        | Total
user@gr.com   | name user   | 5  (this is the only user in all the 5 tables)   
user1@gr.com  | name user1  | 3
user2@gr.com  | name user2  | 3  
user3@gr.com  | name user2  | 2

我尝试了左联接,但只返回了一条记录。..不是列表...我在做什么错了?

1 个答案:

答案 0 :(得分:0)

这种类型的查询需要使用UNION ALL

SELECT b.email, b.name, count(*)
from 
(
SELECT email from table1
UNION ALL
SELECT email from table2
UNION ALL
SELECT email from table3
UNION ALL
SELECT email from table4
UNION ALL
SELECT email from table5
) as a inner join employess b on a.email = b.email
GROUP BY b.email, b.name