我正在计算用户帐户的唯一 ip 访问。我在检查总访问量与分组用户帐户访问量时得到不同的结果
我的表结构是这样的
id userid userip status date
1 xxxx 11111 1 unix timestamp
2 yyyy 11122 1 unix timestamp
3 zzzz 11133 1 unix timestamp
4 cccc 11144 1 unix timestamp
我正在做这样的查询
$date1 = strtotime("yesterday midnight");
$date2 = strtotime("today midnight");
SELECT `userid`, COUNT(DISTINCT `userip`) AS `total` FROM `stats`
WHERE (`date` >= $date1 AND `date` < $date2) AND `status`=1
结果为 5644
但是当我按 userid
分组时结果不同
$date1 = strtotime("yesterday midnight");
$date2 = strtotime("today midnight");
SELECT `userid`, COUNT(DISTINCT `userip`) AS `total` FROM `stats`
WHERE (`date` >= $date1 AND `date` < $date2) AND `status`=1 GROUP BY `userid`
while($row=mysqli_fetch_assoc($result)){
$total=$total+$row['total'];
}
结果为 6312
请看为什么group by的结果不一样
谢谢
编辑
如果我不计算 DISTINCT
,结果是正确的
最佳答案
很明显 count
不会匹配,因为在您使用 distinct with count 的第一个查询中,现在获取的行是 5644
。
其中可能有 2,3,4,5
这样的计数,所以如果您需要与 group by
相同的计数,您需要添加所有计数列这将与您的分组查询相同
如果您需要唯一用户,请使用以下查询
SELECT DISTINCT `userip` AS `userip` FROM `stats`
WHERE (`date` >= $date1 AND `date` < $date2) AND `status`=1
对于拥有唯一ip的用户
SELECT userid,userip from stats GROUP BY userip HAVING COUNT(*) >=1
关于php - MySQL group by 的结果不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43972397/