简体   繁体   中英

mysql query takes to much time

I want to optimize this query becouse it takes to much time to return records

SELECT 
    u.*, 
    s.legal_name AS structure_name, 
    ui.id AS userinfo_id, 
    ui.structure_id AS structure_id, 
    ui.lrn_user, 
    ui.gender, 
    ui.fiscal_code, 
    ui.prov, 
    ui.phone, 
    ui.school_name, 
    ui.school_codice_meccanografico, 
    us.status, us.date AS status_date, 
    CONCAT(u.lastname,' ',u.firstname) AS fullname, 
    CONCAT(u.firstname,' ',u.lastname) AS display_name, 
    uu.username AS created_by_name, 
    g.group_names, 
    IF(u.website_id = 0,'Sito Web principale', w.name) AS website_name 
FROM fcf_users AS u 
LEFT JOIN ( 
    SELECT 
        gu.user_id, 
        GROUP_CONCAT(gg.name SEPARATOR ', ') AS group_names 
    FROM fcf_user_user_groups gu 
    JOIN fcf_user_groups gg ON gg.id = gu.group_id 
    GROUP BY user_id 
) g ON g.user_id = u.id 
LEFT JOIN fcf_users_userinfo AS ui ON ui.user_id = u.id 
LEFT JOIN fcf_users_user_statuses AS us ON us.user_id = u.id 
LEFT JOIN fcf_structures_structures AS s ON s.id = ui.structure_id 
LEFT JOIN fcf_users AS uu ON uu.id = u.created_by 
LEFT JOIN fcf_websites AS w ON w.id = u.website_id 
WHERE 
    u.id IN (SELECT user_id FROM fcf_user_user_groups WHERE group_id = '8') 
    AND u.id IN (SELECT user_id FROM fcf_user_user_groups WHERE group_id = '8') 
    AND ui.lrn_user = '0' 
ORDER BY fullname ASC 
LIMIT 0,25

If anyone can help, thanks

Turn it inside-out. That is, first use a 'derived' table to locate 25 users you want. Then gather the rest of the info.

What you have gathers all the info (including all the JOIN work) for all the users, then sorts and peels off 25.

It will be something like:

SELECT  -- lots of stuff
    FROM ( SELECT  u.id,
                   CONCAT(u.lastname,' ',u.firstname) AS fullname
              FROM  fcf_users AS u
              JOIN  fcf_user_user_groups AS ug ON ...
              JOIN  fcf_users_userinfo AS ui ON ui.user_id = u.id
              WHERE  ug.group_id = '8'
                AND  ui.lrn_user = '0'
              ORDER BY u.lastname, u.firstname  -- now sargeable
              LIMIT 25
         ) AS u25
    JOIN ....  -- whatever tables are needed to get the rest of the columns
    ORDER BY u25.fullname  -- yes, again, but now using the CONCAT
    -- no limit here

Also:

u:  INDEX(lastname, firstname, id)

user_user_group is a "many-t0=many mapping" table? If so, follow the indexing advice here: http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table Ditto for any other many:many tables.

Note how I put into the derived table only the tables needed to achieve the LIMIT .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM