如何获取多个表的项目数

时间:2010-12-09 16:07:59

标签: mysql sql count

我有多个表(每天一个),它们都具有相同的结构:ID,srcIP,time。

我可以使用以下内容获取每天的总行数:

SELECT
  (SELECT COUNT(*) FROM Day1) as Day1Count, 
  (SELECT COUNT(*) FROM Day2) as Day2Count,
  (SELECT COUNT(*) FROM Day3) as Day3Count

但那只是给了我

Day1count  Day1count Day1count
102        148       131

但是,如何才能获得每天每个IP地址的总计数?并非每天都有IP。

srcIP       D1  D2  D3
172.16.0.1      99  34
172.16.0.2  55      22
172.16.0.3  47  49  75

提前致谢!

1 个答案:

答案 0 :(得分:1)

要按ip和按天获取计数,最简单的方法是展平查询:

SELECT 'day1' AS day, srcIP, count(*) AS count FROM Day1 GROUP BY srcIP
UNION
SELECT 'day2' AS day, srcIP, count(*) AS count FROM Day2 GROUP BY srcIP
UNION
SELECT 'day3' AS day, srcIP, count(*) AS count FROM Day3 GROUP BY srcIP

然后将其转置到您的应用中以获得您想要的表格格式。

<强>替代地

您也可以加入IP:

SELECT srcIP, d1.count, d2.count, d3.count
FROM (SELECT srcIP, count(*) AS count FROM Day1 GROUP BY srcIP) d1
LEFT JOIN (SELECT srcIP, count(*) AS count FROM Day2 GROUP BY srcIP) d2 USING (srcIP)
LEFT JOIN (SELECT srcIP, count(*) AS count FROM Day3 GROUP BY srcIP) d3 USING (srcIP)

但是在这里你将丢失不在Day1中的IP,除非你首先从一整天的UNION做一个SELECT DISTINCT srcIP,这是非常昂贵的。基本上,这种表结构对于这种聚合来说太容易了。