简体   繁体   中英

Count separate row on same id from different table : MySQL

I want to count the number of aircon and client under the same usr_id . Here's my resources:

clients_db

+---------+--------+
| clnt_id | usr_id |
+---------+--------+
|    1    |   a1   |
+---------+--------+
|    2    |   a1   |
+---------+--------+
|    3    |   a2   |
+---------+--------+
|    4    |   a1   |
+---------+--------+

aircon_client_db

+---------+--------+---------+
|  ac_id  | usr_id | clnt_id |
+---------+--------+---------+
|    1    |   a1   |    1    |
+---------+--------+---------+
|    2    |   a2   |    2    |
+---------+--------+---------+
|    3    |   a2   |    1    |
+---------+--------+---------+
|    4    |   a2   |    3    |
+---------+--------+---------+

According to the tables above. I want to count

  1. how many clnt_id under the same usr_id
  2. how many ac_id under the same usr_id

So I coded:

select count(acdb.ac_id) as nAC,
count(clnt.clnt_id) as nClnt 
from aircon_client_db acdb 
left join clients_db clnt on clnt.usr_sid=acdb.usr_sid 
where acdb.usr_sid='a1'

I expect the answer as following:

  1. 3
  2. 1

But as I tested. My results are the same for both count - 4. Where did I wrong?

You want to count:
clnt_id s from the table clients_db and
ac_id s from the table aircon_client_db
for usr_sid='a1' , right?
I don't see the necessity of joining the tables.
You can count separately with 2 subqueries in the same query:

select 
  (select count(ac_id) from aircon_client_db where usr_sid = 'a1') as nAC,
  (select count(clnt_id) from clients_db where usr_sid = 'a1') as nClnt

If there is a case of duplicate clnt_id s in clients_db or duplicate ac_id s in aircon_client_db , then use:
count(distinct clnt_id) and count(distinct ac_id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM