匹配列

时间:2012-10-26 06:22:35

标签: mysql sql

我想知道是否有办法显示一组匹配或不同的数据..比如说我有三张桌子,

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 i need-
ip  |isp    |infection
----------------------
1   |aaaa   |malware
1   |aaaa   |ddos
2   |bbbb   |malware
2   |bbbb   |other
3   |cccc   |ddos
3   |cccc   |trojan
4   |dddd   |ddos
4   |dddd   |trojan
5   |eeee   |trojan
6   |ffff   |other
6   |ffff   |

问题是我不知道在这个场景中使用什么方法,我使用这个查询full join

SELECT a. * , b. * , c. *
FROM tbl_1 a
LEFT OUTER JOIN tbl_2 b
USING ( ip, isp, infection )
LEFT OUTER JOIN tbl_3 c
USING ( ip, isp, infection )
UNION
SELECT a. * , b. * , c. *
FROM tbl_2 b
LEFT OUTER JOIN tbl_1 a
USING ( ip, isp, infection )
LEFT OUTER JOIN tbl_3 c
USING ( ip, isp, infection )
UNION
SELECT a. * , b. * , c. *
FROM tbl_3 c
LEFT OUTER JOIN tbl_1 a
USING ( ip, isp, infection )
LEFT OUTER JOIN tbl_2 b
USING ( ip, isp, infection )

但这会以不同的方式给出结果,

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

请帮助我这个,我想只显示3列数据..

非常感谢:)

4 个答案:

答案 0 :(得分:3)

这很简单UNION

SELECT ip, isp, infection FROM tbl_1
UNION
SELECT ip, isp, infection FROM tbl_2
UNION
SELECT  ip, isp, infection FROM tbl_3
ORDER BY IP

SQLFiddle Demo

答案 1 :(得分:1)

SELECT * 
FROM   (
        SELECT * FROM tbl_1 
        UNION 
        SELECT * FROM tbl_2 
        UNION 
        SELECT * FROM tbl_3
       ) AS t
ORDER BY ip, isp

答案 2 :(得分:1)

您应该UNION这三个表并执行GROUP BY删除重复项:

SELECT ip, isp, infection 
FROM tbl_1

UNION

SELECT ip, isp, infection 
FROM tbl_2

UNION

SELECT  ip, isp, infection 
FROM tbl_3

GROUP BY ip, isp, infection

ORDER BY IP

答案 3 :(得分:1)

这不是最优雅的解决方案,但是这样的工作会是什么? (假设我的语法正确......暂时不能测试它):

SELECT * FROM ((SELECT * FROM tbl_1) UNION (SELECT * FROM tbl_2) UNION (SELECT * FROM tbl_3)) ORDER BY isp DESC, infection DESC;