2015-06-02 31 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>