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

MySQL Count registros coincidentes de varias tablas

Otra forma de reescribir esta consulta.

Agrupe y cuente en cada mesa individualmente, luego únase:

SELECT  a.id, 
        COALESCE(b.t1, 0) AS t1,
        COALESCE(c.t2, 0) AS t2,
        COALESCE(d.t3, 0) AS t3
FROM
        entity a
    LEFT JOIN
        ( SELECT ei,
                 COUNT(*) AS t1
          FROM table1
          GROUP BY ei
        ) AS b
            ON a.id = b.ei
    LEFT JOIN
        ( SELECT ei,
                 COUNT(*) AS t2
          FROM table2
          GROUP BY ei
        ) AS c
            ON a.id = c.ei
    LEFT JOIN
        ( SELECT ei,
                 COUNT(*) AS t3
          FROM table3
          GROUP BY ei
        ) AS d
            ON a.id = d.ei
  ;

Definitivamente deberías agregar un índice en (ei) en cada una de las 3 mesas, si no tienes una.