简体   繁体   English

计算来自不同表的相同ID上的单独行:MySQL

[英]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 . 我想计算同一usr_id下的usr_id和client的usr_id Here's my resources: 这是我的资源:

clients_db clients_db

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

aircon_client_db 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 多少clnt_id相同下usr_id
  2. how many ac_id under the same usr_id 多少ac_id相同下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 3
  2. 1 1

But as I tested. 但是正如我测试过的那样。 My results are the same for both count - 4. Where did I wrong? 我的结果在两个方面都是相同的-4.我在哪里弄错了?

You want to count: 您要计算:
clnt_id s from the table clients_db and clnt_id从表S = clients_db
ac_id s from the table aircon_client_db aircon_client_db ac_id s
for usr_sid='a1' , right? 对于usr_sid='a1' ,对吗?
I don't see the necessity of joining the tables. 我认为没有必要加入表格。
You can count separately with 2 subqueries in the same query: 您可以在同一查询中使用2个子查询分别计数:

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: 如果有重复的情况下clnt_id S IN clients_db或重复ac_id S IN aircon_client_db ,然后使用:
count(distinct clnt_id) and count(distinct ac_id) count(distinct clnt_id)count(distinct ac_id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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