0

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?

4
  • Your tables do not appear to be normalized. Please explain what each table is supposed to be doing here. Commented Jun 3, 2019 at 8:16
  • 'mechanic id' - i see no such column? Commented Jun 3, 2019 at 8:17
  • @TimBiegeleisen usr_id=mechanic logged in, client_db=mechanic's clients, aircon_client_db=client's aircon detail Commented Jun 3, 2019 at 8:21
  • 'Where did I wrong?' - If you are analysing by user_id I would expect to see user_id in the select and a group by user_id. But I think the you conception is flawed and the query should be driven by whatever table holds the user details. Commented Jun 3, 2019 at 8:29

1 Answer 1

1

You want to count:
clnt_ids from the table clients_db and
ac_ids 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_ids in clients_db or duplicate ac_ids in aircon_client_db, then use:
count(distinct clnt_id) and count(distinct ac_id)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.