user1813867
user1813867

Reputation: 1055

How to get the related count or two different tables with related records?

I have an account table that has two related tables. I'm trying to get an independent count of the related rows for those two tables but when I do the second join it changes the results from the first count.

account

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 |

So as you can see account 7341383 has one related aa record (3442287) and 9 unique ab records. I'd like to write a group by statement that gives me the count of those two tables' related records. A single group by works, but one that contains two joins ends up skewing the results.

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     |

How can I get the counts to operating independently?

Upvotes: 0

Views: 37

Answers (2)

lyz
lyz

Reputation: 548

you can group by multiple columns so you have to add a group by aa.id too

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, aa.id;

Upvotes: 0

Barmar
Barmar

Reputation: 781058

Use 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;

Upvotes: 1

Related Questions