[Solved] MySQL Make it faster,add members count to family table

How to optimize this SQL query?

In case you have your own slow SQL query, you can optimize it automatically here.

For the query above, the following recommendations will be helpful as part of the SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 9): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
The optimized query:
SELECT
        f.family_id,
        f.family_code,
        f.lname,
        f.fname,
        f.mname,
        f.exname,
        f.remark,
        p.*,
        b.*,
        m.*,
        (SELECT
            SUM(family_members.member_id != 0) 
        FROM
            family_members 
        WHERE
            family_members.family_id = f.family_id) AS MEMCOUNT 
    FROM
        family_profile f 
    LEFT JOIN
        purok p 
            ON f.home_address = p.purok_id 
    LEFT JOIN
        barangay b 
            ON p.brgy_id = b.brgy_id 
    LEFT JOIN
        municipality m 
            ON b.mun_id = m.mun_id 
    WHERE
        f.family_id != 0 
        AND f.family_code != '' 
    ORDER BY
        mun_name,
        brgy_name,
        purok_name,
        f.lname,
        f.fname

Related Articles



* original question posted on StackOverflow here.