我遇到了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会怎样?
答案 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.service
和s.id
中包含select
和group 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}}
我不确定哪种计数最合适。