【问题标题】:mysql query takes to much timemysql查询需要很多时间
【发布时间】:2020-03-14 22:02:46
【问题描述】:

我想优化这个查询,因为返回记录需要很长时间

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

如果有人可以帮忙,谢谢

【问题讨论】:

  • 正确格式化查询是优化的第一步。
  • 此外,除了所有相关表的 SHOW CREATE TABLE 语句之外,关于查询性能的问题总是需要对给定查询的 EXPLAIN
  • 您的where 子句有两次相同的IN 条件。
  • 我删除了IN,但我仍然需要很多时间

标签: mysql query-optimization


【解决方案1】:

把它翻过来。也就是说,首先使用“派生”表来定位您想要的 25 个用户。 然后收集其余信息。

您所拥有的内容为所有用户收集所有信息(包括所有JOIN工作),然后分类并剥离25。

会是这样的:

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

还有:

u:  INDEX(lastname, firstname, id)

user_user_group 是“many-t0=many 映射”表吗?如果是这样,请遵循此处的索引建议:http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table 其他任何多:多表也是如此。

注意我是如何只将实现LIMIT 所需的表放入派生表中的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多