Anda harus memfaktorkan ulang kueri Anda. Anda dapat melakukannya dengan menyusun ulang cara kueri mengumpulkan data. Bagaimana?
- Terapkan klausa WHERE terlebih dahulu
- Ajukan GABUNG terakhir
Ini pertanyaan asli Anda:
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
Ini pertanyaan baru Anda
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 saya mengubah member m
ke SELECT * FROM member m WHERE member_id = 27
jika Anda memerlukan informasi tentang anggota 27. Saya juga menambahkan IFNULL
fungsi untuk setiap hasil untuk menghasilkan 0 jika jumlah kasus adalah NULL.
Anda harus benar-benar yakin
- member_id adalah kunci utama dari tabel anggota
- member_id diindeks di table1, table2, dan table3
Cobalah !!!