我有这个查询,它按预期工作
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
此查询也可按预期工作:
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
但我如何将这两者合二为一呢?
我试过
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
在这种情况下,值sclr2是正确的,但sclr3与sclr2相同。我做错了什么?
答案 0 :(得分:1)
您可以通过制作子查询来组合这些:
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;
如另一个答案所述,count(distinct)
也可以。然而,它产生了一个中间表,它是"日期"的笛卡尔积。和#34;用户代理"。因此,如果有100个日期和100个用户代理,则中间表将有10,000行 - 如果您的数据有很多这样的示例,则处理时间和中间存储要求可能会变得过高。
答案 1 :(得分:0)
尝试使用
COUNT(DISTINCT d1_.id) AS sclr2, COUNT(DISTINCT u2_.id)