2012-03-18 50 views
0

我有一個USER_ID鍵,在表A表B表C顯示出來。MYSQL COUNT函數在多個表

表A

User_id value 
1  A 
2  B 
3  C 

表B

User_id value 
1  A 
1  B 
1  C 

表C

User_id value 
1  A 
1  B 
0  C 

TA是上USER_ID唯一的。我試圖用一個查詢中的user_id來獲取表B和表C中的出現次數。

我想:

SELECT tA.user_id, (SELECT count(*) FROM tB as countB GROUP BY tA.user_id),(SELECT count(*) FROM tC as countC GROUP BY tA.user_id) FROM tA where tA.user_id='1' 

回答

0

我想這是你想要做什麼:

select ta.user_id, 
    (select count(*) from tb where ta.user_id = tb.user_id) CountB, 
    (select count(*) from tc where ta.user_id = tc.user_id) CountC 
from ta 
where ta.user_id = 1 
0

您是否嘗試過使用次數(不同的)?

SELECT tA.user_id, count(distinct tB.id), count(distinct tC.id) FROM tA, tB, tC 
WHERE tA.user_id=tB.user_id AND tA.user_id=tC.user_id AND tA.user_id='1'; 

編輯:這是假設你在tB和tC上有一個唯一的字段。