mysql - MySQL 查询速度慢 - 如何才能加快速度?

标签 mysql sql performance

此内容已编辑 - 我已尝试加快速度,但仍然很慢 - 有人可以提供更多帮助吗?

SELECT DISTINCT d.`group_ID`,
  CONCAT(u.fname, ' ', u.lname) AS uname,
  u.corp_id,
  c.`corp_name`,
  u.`user_username`,
  u.location,
  (
    SELECT email 
    FROM users 
    WHERE role = 'Level 4' 
      AND location = d.location 
      AND email NOT LIKE '%manager.%' 
    LIMIT 1
  ) AS trainer,
  u.`email`,
  GROUP_CONCAT(
    DISTINCT d.title 
    ORDER BY d.title SEPARATOR ', '
  ) AS docs 
FROM regulatory d 
  LEFT JOIN users u 
    ON u.user_id = d.`group_ID` 
    AND u.`role` = 'Level 6' 
  LEFT JOIN corporations c 
    ON c.`corp_id` = u.`corp_id` 
WHERE d.`spare1` <> 'green.gif' 
  AND u.`officialjobtitle` <> 'none' 
  AND d.`date_updated` < NOW() 
  AND (u.`corp_id` IN (1)) 
GROUP BY d.`group_ID` 
ORDER BY corp_id,
  u.`location`,
  uname ;

最佳答案

  • 您否定 regulatory 的左连接至users在哪里 子句,因此使用 INNER JOIN对于这两个表
  • 使用INNER JOIN对公司来说是否可能(我只是不知道是否可行)
  • 删除 DISTINCT。您已经在执行GROUP BY如果做得正确的话,distinct 将是完全多余的(因为它不会做任何 GROUP BY 不能做的事情)
  • 我会尝试替换 trainer 的相关子查询使用已分组的“派生表”,因此您无需将行相乘
  • 使用 GROUP BY 时在MySQL中从不依赖“扩展”。始终指定生成唯一行所需的所有字段(就像在几乎所有其他 SQL 兼容的 RDBMS 中一样)

确保连接中涉及的所有字段都有索引,如果可能的话,还有 where 子句中使用的字段。

检查解释计划。

建议修改:

SELECT
      d.`group_ID`
    , CONCAT ( u.fname , ' ' , u.lname ) AS uname
    , u.corp_id
    , c.`corp_name`
    , u.`user_username`
    , u.location
    , MAX(l4.trainer) as trainer
    , u.`email`
    , GROUP_CONCAT(DISTINCT d.title ORDER BY d.title SEPARATOR ', ') AS docs
FROM regulatory d
INNER JOIN users u ON d.`group_ID` = u.user_id
                   AND u.`role` = 'Level 6'
LEFT JOIN corporations c ON u.`corp_id` = c.`corp_id`
LEFT JOIN (
        SELECT location, MAX(email) AS trainer
        FROM users
        WHERE ROLE = 'Level 4'
            AND email NOT LIKE '%manager.%'
        GROUP BY location
        ) l4 ON d.location = l4.location
WHERE d.`spare1` <> 'green.gif'
    AND u.`officialjobtitle` <> 'none'
    AND d.`date_updated` < NOW()
    AND u.`corp_id` IN (1)
GROUP BY
      d.`group_ID`
    , u.fname
    , u.lname
    , u.corp_id
    , c.`corp_name`
    , u.`user_username`
    , u.location
    , u.`email`
ORDER BY
      corp_id
    , u.`location`
    , uname
;

关于mysql - MySQL 查询速度慢 - 如何才能加快速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25718606/

相关文章:

python - 像 HTML5 Navigation Timing 那样用 Python 测量页面速度和网络时间?

MySQL 工作台 : No Password Is Set For This Account

java - Oracle DB表与 View (物化 View )的关系

php - 为什么我的 mysql 连接中有一个 "Invalid argument supplied for foreach"?

带有 Rails ActiveRecord 的 SQL UNION

database - 按随机排序() : how many rows can a table hold before becoming the worst solution?

php - 为什么这个登录表单代码不起作用?

sql - 按存在重复项的单列获取唯一行

MySQL如何填充范围内的缺失日期?

java - 执行包含 java -jar Runtime.exec() 的 shell 脚本,它将使用哪个 java,操作系统级别还是应用程序级别