MySQL,得到两个查询的总和

时间:2018-02-06 11:47:02

标签: mysql sql outer-join

我有三个不同的表,Product有不同的列和结构,假设

产品1 产品2 产品3

所以,我试图获得具有相同user_id的三个表的计数(*),即foreach user_id字段。

表格 - 产品1

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

表格 - 产品2

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

表格 - 产品3

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

他们向我user_id字段和count(*)

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

6 个答案:

答案 0 :(得分:3)

有三个具有相同结构的表通常表明数据库设计不佳。您应该找出将表合并到一个表中的方法。

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

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确保包含所有三个表中的用户。

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

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

答案 1 :(得分:2)

使用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`;

答案 2 :(得分:2)

你可以总结所有

的结果
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

答案 3 :(得分:2)

是的,你可以:)

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

答案 4 :(得分:0)

请在下面尝试。没有尝试在db中,因此可能会出现语法错误。

选择p.user_id,sum(total)from( 选择P.user_id,通过P.user_id计算product1 p组的总计() 联合所有 选择P.user_id,通过P.user_id从product2 p组计算()总计 联合所有 选择P.user_id,通过P.user_id从product3 p group计算总数(*) )a

答案 5 :(得分:0)

是的,我们可以根据我们的要求,使用tablesjoin汇总来自不同union的结果。在您的情况下,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;
相关问题