MySQL,获取两个查询的总和

MySQL, get sum of two queries

我有三个关于 Product 的不同表,它们具有不同的列和结构,假设

Product1, Product2, Product3

因此,我正在尝试获取具有相同 user_id 的三个表的计数 (*) 总和,即 foreach user_id 字段。

Table - 产品 1

select P.user_id, count(*) 
from Product1 P  
group by P.user_id

Table - Product2

select P.user_id, count(*) 
from Product2 P  
group by P.user_id

Table - Product3

select P.user_id, count(*) 
from Product3 P  
group by P.user_id

他们给了我 user_id 字段和 count(*),

我可以添加 count(*), foreach user_id 字段的结果吗?提前谢谢

使用 UNION 合并结果,然后进行加法。

查询

select t.`user_id`, sum(`count`) as `total` from(
    select `user_id`, count(*) as `count`
    from `Product1`
    group by `user_id`
    union all
    select `user_id`, count(*) 
    from `Product2` 
    group by `user_id`
    union all
    select `user_id`, count(*) 
    from `Product3`
    group by `user_id`
) t
group by t.`user_id`;

具有三个具有相同结构的 table 通常是数据库设计不佳的标志。您应该找出将 table 组合成单个 table.

的方法

无论如何,您都可以汇总结果。一种方式是:

select user_id, sum(cnt)
from ((select user_id, count(*) as cnt
       from product1
       group by user_id
      ) union all
      (select user_id, count(*) as cnt
       from product2
       group by user_id
      ) union all
      (select user_id, count(*) as cnt
       from product3
       group by user_id
      )
     ) up
group by user_id;

您想使用 union all 而不是 join,因为 MySQL 不支持 full outer joinUnion all 确保包括所有三个 table 的用户。

聚合两次(在子查询和外部查询中)允许 MySQL 将索引用于内部聚合。这可能是一个性能优势。

此外,如果您要查找特定用户或一组用户,请在子查询中使用 where 子句。这比将所有数据放在子查询中然后进行过滤更有效(在 MySQL 中)。

您可以对 union all 的结果求和

select user_id, sum(my_count)
from (

select P.user_id, count(*)  my_count
from Product1 P  
group by P.user_id
UNION ALL
select P.user_id, count(*) 
from Product2 P  
group by P.user_id
UNION ALL 
select P.user_id, count(*) 
from Product3 P  
group by P.user_id ) t
group by user_id

是的,你可以:)

SELECT SUM(userProducts) userProducts 
FROM (
    SELECT count(user_id) userProducts FROM Product1 WHERE user_id = your_user_id
    UNION ALL
    SELECT count(user_id) userProducts FROM Product2 WHERE user_id = your_user_id
    UNION ALL
    SELECT count(user_id) userProducts FROM Product3 WHERE user_id = your_user_id
) s

请尝试以下。没有在数据库中尝试过,所以可能会出现语法错误。

select p.user_id ,sum(total) from ( select P.user_id,product1 p 组的计数()总计 P.user_id 联合所有 select P.user_id,product2 p 组的计数()总计 P.user_id 联合所有 select P.user_id,product3 p 组的计数 (*) 总数 P.user_id ) 一个

是的,我们可以根据需要使用 joinunion 汇总来自不同 tables 的结果。在您的情况下,Union All 将完美运行,并且可以使用 count(1) 而不是 count(*) 来编写优化查询,因为它使用 table 的第一个索引,它通常是聚集索引。

select user_id, sum(cnt)
from ((select user_id, count(1) as cnt
       from product1
       group by user_id
      ) union all
      (select user_id, count(1) as cnt
       from product2
       group by user_id
      ) union all
      (select user_id, count(1) as cnt
       from product3
       group by user_id
      )
     ) a
group by user_id;