1

只是出于好奇,有没有一种方法可以让我获得 2 个或更多表中匹配数据的计数。如,如果我们得到以下 3 个表,

tbl_1-
ip  |isp    |infection
----------------------
1   |aaaa   |malware
2   |bbbb   |malware
3   |cccc   |ddos
3   |cccc   |trojan
4   |dddd   |ddos

tbl_2-
ip  |isp    |infection
----------------------
1   |aaaa   |malware
3   |cccc   |ddos
4   |dddd   |trojan
5   |eeee   |trojan
6   |ffff   |other

tbl_3-
ip  |isp    |infection
----------------------
1   |aaaa   |ddos
6   |ffff   |
2   |bbbb   |other

我能得出如下所示的答案吗?

Result-
ip  |isp    |infection  |Match Count
------------------------------------
1   |aaaa   |malware    |2      
1   |aaaa   |ddos       |1      
2   |bbbb   |malware    |1
2   |bbbb   |other      |1
3   |cccc   |ddos       |2
3   |cccc   |trojan     |1
4   |dddd   |ddos       |1
4   |dddd   |trojan     |1
5   |eeee   |trojan     |1
6   |ffff   |other      |1
6   |ffff   |           |1

谢谢 :)

4

3 回答 3

5

您需要为此使用UNION ALL不仅是 UNION)以允许重复

SELECT ip, isp, infection, COUNT(*)
FROM 
(
SELECT ip, isp, infection FROM tbl_1
UNION ALL
SELECT ip, isp, infection FROM tbl_2
UNION ALL
SELECT  ip, isp, infection FROM tbl_3
) x
GROUP BY ip, isp, infection

SQLFiddle 演示

于 2012-10-26T08:51:50.957 回答
2

您应该对所有三个表执行 UNION ALL,然后按 ip、isp、感染列运行 GROUP BY。

SELECT ip, isp, infection, COUNT(*) 'Match Count'
FROM
(
    SELECT * FROM tbl_1
    UNION ALL
    SELECT * FROM tbl_2
    UNION ALL
    SELECT * FROM tbl_3
) AS A
GROUP BY ip, isp, infection
于 2012-10-26T08:49:26.433 回答
0

是的,您可以使用 COUNT() 函数 http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_count

于 2012-10-26T08:50:25.340 回答