如何获取相关记录的相关计数或两个不同的表?

时间:2016-01-26 21:49:57

标签: mysql

我有一个包含两个相关表的帐户表。我试图获得这两个表的相关行的独立计数,但是当我进行第二次连接时,它会更改第一次计数的结果。

帐户

account_service_a account_service_b

select a.id as account_id, aa.id as aa_id, ab.id as ab_id 
from account a 
inner join account_service_a aa on aa.account_id = a.id 
inner join account_service_b ab = ab.account_id = a.id;

+------------+---------+----------+
| account_id | aa_id   | ab_id    |
+------------+---------+----------+
|    7341383 | 3442287 | 20966936 |
|    7341383 | 3442287 | 24671972 |
|    7341383 | 3442287 | 31195473 |
|    7341383 | 3442287 | 31195658 |
|    7341383 | 3442287 | 31195730 |
|    7341383 | 3442287 | 31195798 |
|    7341383 | 3442287 | 31195925 |
|    7341383 | 3442287 | 31195966 |
|    7341383 | 3442287 | 31196022 |

因此,您可以看到帐户7341383有一个相关的aa记录(3442287)和9个唯一的ab记录。我想写一个group by语句,给我这两个表的相关记录的计数。单个按工作组,但包含两个连接的组最终会使结果偏斜。

select a.id as account_id, count(aa.id) as aa_count 
from account a 
inner join account_service_a aa on aa.account_id = a.id 
group by a.id

+------------+---------+
| account_id | aa_count| 
+------------+---------+
|    7341383 |    1    | 


select a.id as account_id, count(aa.id) as aa_count, count(ab.id) as ab_count 
from account a 
inner join account_service_a aa on aa.account_id = a.id 
inner join account_service_b ab = ab.account_id = a.id 
group by a.id;

+------------+---------+----------+
| account_id | aa_id   | ab_id    |
+------------+---------+----------+
|    7341383 |    9    |    9     |

如何让计数独立运作?

2 个答案:

答案 0 :(得分:1)

使用COUNT(DISTINCT)

select a.id as account_id, count(DISTINCT aa.id) as aa_count, count(*) as ab_count 
from account a 
inner join account_service_a aa on aa.account_id = a.id 
inner join account_service_b ab on ab.account_id = a.id 
group by a.id;

答案 1 :(得分:0)

您可以按多列进行分组,因此您也必须按aa.id添加组

选择a.id作为account_id,count(aa.id)作为aa_count,count(ab.id)作为ab_count来自帐户a inner join account_service_a aa on aa.account_id = a.id inner join account_service_b ab = ab.account_id = a.id group by a.id,aa.id;