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

MySQL COUNT di più join sinistri - ottimizzazione

Dovresti rifattorizzare la tua query. Puoi farlo riordinando il modo in cui la query raccoglie i dati. Come?

  • Applica prima la clausola WHERE
  • Applica JOIN per ultimi

Ecco la tua domanda originale:

SELECT t1.num1,t2.num2,t3.num3 
FROM member m 
LEFT JOIN 
( 
   SELECT member_id,COUNT(*) as num1 
   FROM table1 
   GROUP BY member_id 
) t1 ON t1.member_id = m.member_id 
LEFT JOIN 
( 
   SELECT member_id,COUNT(*) as num2 
   FROM table2 
   GROUP BY member_id 
) t2 ON t2.member_id = m.member_id 
LEFT JOIN 
( 
   SELECT member_id,COUNT(*) as num3 
   FROM table3 
   GROUP BY member_id 
) t3 ON t3.member_id = m.member_id 
WHERE m.member_id = 27 

Ecco la tua nuova domanda

SELECT
   IFNULL(t1.num1,0) num1,
   IFNULL(t1.num2,0) num2,
   IFNULL(t1.num3,0) num3
FROM
(
   SELECT * FROM member m 
   WHERE member_id = 27
) 
LEFT JOIN 
( 
   SELECT member_id,COUNT(*) as num1 
   FROM table1 
   WHERE member_id = 27
   GROUP BY member_id 
) t1 ON t1.member_id = m.member_id 
LEFT JOIN 
( 
   SELECT member_id,COUNT(*) as num2 
   FROM table2 
   WHERE member_id = 27
   GROUP BY member_id 
) t2 ON t2.member_id = m.member_id 
LEFT JOIN 
( 
   SELECT member_id,COUNT(*) as num3 
   FROM table3 
   WHERE member_id = 27
   GROUP BY member_id 
) t3 ON t3.member_id = m.member_id 
;

A proposito, ho cambiato member m in SELECT * FROM member m WHERE member_id = 27 nel caso avessi bisogno di informazioni sul membro 27. Ho anche aggiunto il IFNULL funzione a ciascun risultato per produrre 0 nel caso in cui il conteggio sia NULL.

Devi essere assolutamente sicuro

  • member_id è la chiave primaria della tabella membro
  • member_id è indicizzato in table1, table2 e table3

Provalo!!!