2015-06-02 110 views
0

我需要一個查詢來查找基於多個表的計數。請檢查以下詳細信息Mysql根據連接表拆分列值

我有3個表作爲table_1,table_2,table_3和table_1是主表,其他2是從主繼承。這些表具有profile_id列的通用值。檢查此示例查詢計數器

SELECT COUNT(profile_id) 
from table_1 
WHERE profile_id IN (SELECT profile_id FROM table_2) 

以上查詢返回基於table_2 profile id的計數。但我需要的所有表單獨查詢類似如下

SELECT COUNT(profile_id) as table_2count, 
     COUNT(profile_id) as table_3count 
FROM table_1 WHERE (the two condition) 

在上面的查詢table_2count是基於TABLE_2概況和table_3count將基於該TABLE_3。我怎樣才能將這些值合併爲單個查詢。請建議一些方法來找出計數值。

+0

爲什麼SQL服務器和PHP的標籤在這裏使用? – ughai

+0

是'profile_id'在'table_1'中唯一嗎? – ughai

+0

@ughai。是的profile_id是唯一的.. – satheesh

回答

1

如果profile_idtable_1獨特,你table_2table_3有外鍵,你並不真的需要加入回來TABLE_1,你需要是這樣的。

SELECT 
(SELECT COUNT(distinct profile_id) FROM table_2) table_2count, 
(SELECT COUNT(distinct profile_id) FROM table_3) table_3count 

如果你真的需要加入或沒有定義FKS,你可以在此

SELECT 
    COUNT(distinct t2.profile_id) table_2count, 
    COUNT(distinct t3.profile_id) table_3count 
FROM table_1 t1 
    LEFT JOIN table_2 t2 on t1.profile_id = t2.profile_id 
    LEFT JOIN table_3 t3 on t1.profile_id = t3.profile_id 
1

您可以使用子查詢2實現的是:

SELECT 
     t1.*, -- get all data from t1 + two counts from t2 and t3 
     (SELECT COUNT(t2.profile_id) 
     FROM table_2 t2 
     WHERE t2.profile_id = t1.profile_id) as count2, 
     (SELECT COUNT(t3.profile_id) 
     FROM table_3 t3 
     WHERE t3.profile_id = t1.profile_id) as count3 
    FROM table_1 t1 
    WHERE <your conditions for table_1 go here>