COUNT(*)不正确

时间:2014-01-17 14:29:29

标签: mysql

我遇到了mysql查询的问题。

SELECT switch_id, port_id, isp_service.service, isp_service.id
FROM traffic, isp_service
WHERE datetime>='2013-09-01 00:00:00' 
AND datetime<'2013-09-02 00:00:00'
AND isp_service.id=traffic.isp_service_id
GROUP BY switch_id, port_id 

此查询返回1000行。 现在我想计算每个服务有多少用户,所以我做了:

SELECT ris.id, COUNT(*) as numberOfUsers
FROM 
 (SELECT switch_id, port_id, isp_service.service, isp_service.id
 FROM traffic, isp_service
 WHERE datetime>='2013-09-01 00:00:00' 
 AND datetime<'2013-09-02 00:00:00'
 AND isp_service.id=traffic.isp_service_id
 GROUP BY switch_id, port_id)ris
GROUP BY ris.id
ORDER BY ris.id

现在,如果我总结列numberOfUser,结果大于1000会怎样?

1 个答案:

答案 0 :(得分:0)

您应该了解正确的join语法,并为所有列添加表别名。编写第二个查询的更好方法是:

SELECT ris.id, COUNT(*) as numberOfUsers
FROM (SELECT switch_id, port_id, s.service, s.id
      FROM traffic t join
           isp_service s
           on s.id = t.isp_service_id
      WHERE datetime >= '2013-09-01 00:00:00' AND datetime < '2013-09-02 00:00:00'
      GROUP BY switch_id, port_id
     ) ris
GROUP BY ris.id
ORDER BY ris.id;

此查询存在问题,因为s.services.id中包含selectgroup by,但它们不在switch_id中。这意味着MySQL为它们采用任意值。

目前还不清楚是什么指定了“用户”。如果port_id / id对标识用户,则查询应生成正确的结果。但是,您可能会丢失具有用户的SELECT s.id, count(*) as NumberOfUsers, count(distinct switch_id, port_id) as NumberOfUsers2 FROM traffic t join isp_service s on s.id = t.isp_service_id WHERE datetime >= '2013-09-01 00:00:00' AND datetime < '2013-09-02 00:00:00' GROUP BY s.id; 值。您可以在一个查询中执行此操作:

{{1}}

我不确定哪种计数最合适。