2017-01-01 49 views
1

我有三个表,我需要选择电子邮件和计数表A和表B之间的关系,例如:选择三个表和统计

表A:

ID | email 
1 | [email protected] 
2 | [email protected] 
3 | [email protected] 

表B:

UID | username 
11 | James 
22 | Gabriel 
33 | Jonas 

表C:(A和B之间的关系)

ID | email_id | username_id 
    1 | 1  | 11 
    2 | 1  | 22 
    3 | 2  | 33 

期待结果:

Email  | Totalrelation 
[email protected] | 2 
[email protected] | 1 

我想:

select tableA.email, 
    COUNT(distinct tableC.email_id) AS total from tableA as tableA, tableC as tableC GROUP BY tableC.email_id 

但它没有工作,我总不会错。我该怎么做?

回答

1

连接表,组的数据和统计数为每个组

select a.email, count(c.id) as cnt 
from tableA a 
left join tableC c on c.email_id = a.id 
group by a.email 
+0

我不能这样做,因为C有只有EMAIL_ID和A具有电子邮件值 –

+0

我更新了答案 –

+0

谢谢,这是现在工作很好 –