简体   繁体   English

MySQL在一个查询中多次连接多个计数

[英]MySQL multiple joins with multiple counts in one query

I have this query and it works as expected 我有此查询,它按预期工作

SELECT i0_.address AS address0, COUNT(d1_.id) AS sclr2 
FROM IP i0_ 
LEFT JOIN Date_IP d3_ ON i0_.id = d3_.ip 
LEFT JOIN Date d1_ ON d1_.id = d3_.date 
GROUP BY i0_.address 
ORDER BY sclr2 DESC

This query also works as expected: 此查询也可以按预期工作:

SELECT i0_.address AS address0, COUNT(u2_.id) AS sclr3 
FROM IP i0_ 
LEFT JOIN IP_UserAgent i4_ ON i0_.id = i4_.ip 
LEFT JOIN UserAgent u2_ ON u2_.id = i4_.useragent 
GROUP BY i0_.address 
ORDER BY sclr3 DESC

But How can I combine these two into one? 但是,如何将这两者合而为一呢?

I tried 我试过了

SELECT i0_.address AS address0, COUNT(d1_.id) AS sclr2, COUNT(u2_.id) AS sclr3 
FROM IP i0_ 

LEFT JOIN Date_IP d3_ ON i0_.id = d3_.ip 
LEFT JOIN Date d1_ ON d1_.id = d3_.date 

LEFT JOIN IP_UserAgent i4_ ON i0_.id = i4_.ip 
LEFT JOIN UserAgent u2_ ON u2_.id = i4_.useragent 

GROUP BY i0_.address 
ORDER BY sclr2 DESC

In this case value sclr2 is right but sclr3 is the same as sclr2. 在这种情况下,值sclr2是正确的,但sclr3与sclr2相同。 What Am I doing wrong please? 请问我做错了什么?

You can combine these by making them subqueries: 您可以通过使它们成为子查询来组合它们:

SELECT t1.address0, t1.sclr2, t2.sclr3
FROM (SELECT i0_.address AS address0, COUNT(d1_.id) AS sclr2 
      FROM IP i0_ LEFT JOIN 
           Date_IP d3_ ON i0_.id = d3_.ip LEFT JOIN
           Date d1_
           ON d1_.id = d3_.date 
      GROUP BY i0_.address
     ) t1 JOIN
     (SELECT i0_.address AS address0, COUNT(u2_.id) AS sclr3 
      FROM IP i0_ LEFT JOIN
           IP_UserAgent i4_
           ON i0_.id = i4_.ip LEFT JOIN
           UserAgent u2_
           ON u2_.id = i4_.useragent 
      GROUP BY i0_.address
     ) t2
     on t1.address0 = t2.address0;

As mentioned in another answer, count(distinct) can also work. 如另一个答案所述, count(distinct)也可以工作。 However, it produces an intermediate table which is the cartesian product of the "dates" and the "user agents". 但是,它会生成一个中间表,该表是“日期”和“用户代理”的笛卡尔乘积。 So, if there are 100 dates and 100 user agents, the intermediate table would have 10,000 rows -- and if your data has many examples of this, then the processing time and intermediate storage requirements can become prohibitive. 因此,如果有100个日期和100个用户代理,则中间表将具有10,000行-如果您的数据包含许多示例,则处理时间和中间存储需求可能会变得令人望而却步。

尝试使用

COUNT(DISTINCT d1_.id) AS sclr2, COUNT(DISTINCT u2_.id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM