[英]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.