我需要一个查询来找到基于多个表的计数。请检查以下详细信息

我有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。我如何将这些值合并到单个查询中。请提出一些方法来找出计数值。

最佳答案

如果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


如果您确实需要连接或没有定义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 - MySQL根据联接表拆分列值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30587683/

10-11 05:20
查看更多