我需要一个查询来查找基于多个表的计数。请检查以下详细信息
我有 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配置文件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。我如何将这些值合并到单个查询中。请建议一些找出计数值的方法。
最佳答案
如果 profile_id
在 table_1
中是唯一的,并且您在 table_2
和 table_3
中有外键,则您不需要真的不需要加入 table_1,你需要的是这样的。
SELECT
(SELECT COUNT(distinct profile_id) FROM table_2) table_2count,
(SELECT COUNT(distinct profile_id) FROM table_3) table_3count
如果您确实需要联接或者没有定义 FK,则可以使用此
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
关于Mysql根据连接表分割列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30587683/