Du bør refaktorisere din forespørgsel. Du kan gøre dette ved at omarrangere den måde, forespørgslen indsamler dataene på. Hvordan?
- Anvend WHERE-sætningen først
- Anvend JOINs sidst
Her er din oprindelige forespørgsel:
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
Her er din nye forespørgsel
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
;
BTW jeg ændrede member m
ind i SELECT * FROM member m WHERE member_id = 27
hvis du har brug for information om medlem 27. Jeg tilføjede også IFNULL
funktion til hvert resultat for at producere 0, hvis antallet er NULL.
Du skal være helt sikker
- member_id er den primære nøgle i medlemstabellen
- member_id er indekseret i tabel1, tabel2 og tabel3
Prøv det!!!