sql >> Base de Datos >  >> RDS >> Mysql

Consultas anidadas para contar con dos condiciones

Debe agrupar la columna infection y (ip &ipc ) de manera diferente, luego únase a ellos usando una subconsulta como esta:

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

Ver este SQLFiddle

Nota: Creo que la salida deseada es incorrecta porque:

  1. En Table3 no hay infection para ip=6 pero está en su salida
  2. infection other falta en su salida (en su lugar, hay malware )