[英]Count separate row on same id from different table : MySQL
我想计算同一usr_id
下的usr_id
和client的usr_id
。 这是我的资源:
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 |
+---------+--------+---------+
根据上表。 我要数
clnt_id
相同下usr_id
ac_id
相同下usr_id
所以我编码:
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'
我期望答案如下:
但是正如我测试过的那样。 我的结果在两个方面都是相同的-4.我在哪里弄错了?
您要计算:
clnt_id
从表S = clients_db
和
表aircon_client_db
ac_id
s
对于usr_sid='a1'
,对吗?
我认为没有必要加入表格。
您可以在同一查询中使用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
如果有重复的情况下clnt_id
S IN clients_db
或重复ac_id
S IN aircon_client_db
,然后使用:
count(distinct clnt_id)
和count(distinct ac_id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.