Mysql
 sql >> Database >  >> RDS >> Mysql

Query nidificate per ottenere il conteggio con due condizioni

Devi raggruppare la colonna infection e (ip &ipc ) in modo diverso, quindi unisciti a loro usando una sottoquery come questa:

SELECT t1.ip, t1.isp, t2.infection, t1.ipc, t1. ispc, t2.incount
FROM
    (SELECT ip, isp, infection, COUNT(ip) as ipc, COUNT(isp) as ispc
    FROM (
       SELECT ip, isp, infection
       FROM tbl1
       UNION ALL
       SELECT ip, isp, infection
       FROM tbl2
       UNION ALL
       SELECT ip, isp, infection
       FROM tbl3
       )x
     GROUP BY ip, isp) t1
JOIN
    (SELECT ip, isp, infection, COUNT(infection) as incount
     FROM (
       SELECT ip, isp, infection
       FROM tbl1
       UNION ALL
       SELECT ip, isp, infection
       FROM tbl2
       UNION ALL
       SELECT ip, isp, infection
       FROM tbl3
       )x
    GROUP BY ip, isp,  infection)t2
ON t1.ip = t2.ip
ORDER BY ip, isp, infection Desc

Guarda questo SQLFiddle

Nota: Penso che l'output desiderato sia sbagliato perché:

  1. Nella Table3 non c'è infection per ip=6 ma è nel tuo output
  2. infection other manca nel tuo output (invece c'è malware )