【问题标题】:MySQL query optimization [join]MySQL查询优化[加入]
【发布时间】:2023-03-03 23:10:02
【问题描述】:

我有下一个查询

SELECT 
i.*,
gu.*
vs.*
FROM 
common.global_users gu
LEFT JOIN common.global_users_perms gup ON (gu.global_user_id=gup.global_user_id)
LEFT JOIN p.individuals i ON (gup.parent_id = i.member_id)
LEFT JOIN p.vs ON (i.member_id=vs.member_id AND vs.status IN (1,4))
WHERE gup.region = 'us'
AND gu.user_type=2
AND ((gu.email='specific@email.com') OR (i.email='specific@email.com') OR (gu.username='specific@email.com'))
ORDER BY i.status, vs.member_id;

接下来的计划

+----+-------------+-------+--------+------------------------------------------+------------------+---------+-----------------------------+--------+----------+---------------------------------+
| id | select_type | table | type   | possible_keys                            | key              | key_len | ref                         | rows   | filtered | Extra                           |
+----+-------------+-------+--------+------------------------------------------+------------------+---------+-----------------------------+--------+----------+---------------------------------+
|  1 | SIMPLE      | gu    | ref    | PRIMARY,username,idx_user_type,idx_email | idx_user_type    | 1       | const                       | 524243 |   100.00 | Using temporary; Using filesort |
|  1 | SIMPLE      | gup   | ref    | global_user_id_2                         | global_user_id_2 | 4       | common.gu.global_user_id    |      1 |   100.00 | Using where                     |
|  1 | SIMPLE      | i     | eq_ref | PRIMARY                                  | PRIMARY          | 4       | common.gup.parent_id        |      1 |   100.00 | Using where                     |
|  1 | SIMPLE      |  vs   | ref    | member_id,status                         | member_id        | 4       | p.i.member_id               |      1 |   100.00 |                                 |
+----+-------------+-------+--------+------------------------------------------+------------------+---------+-----------------------------+--------+----------+---------------------------------+

有没有可能让它更快?现在大约需要 12 秒

附:在gu 表中只有两个唯一的type 值。并且该表中的所有记录数都超过 1M。

【问题讨论】:

    标签: mysql query-optimization mysql-slow-query-log


    【解决方案1】:

    您的计划结果可能表明问题“使用临时;使用 filesort' 意味着排序是在磁盘上进行的,可能是因为它太大而无法放入内存。如果可能,您可能希望增加内存限制。

    这也可能与您的排序所针对的列有关。如果您删除您的 ORDER BY,查询是否执行得更快?如果是这种情况,您可能需要查看ORDER BY Optimization

    【讨论】:

    • 是的,没有 ORDER 子句查询在 2 时间内工作得更快,但在我的情况下,来自两个不同表的 order 子句中的字段(并且没有一个来自第一个表)。 In some cases, MySQL cannot use indexes to resolve the ORDER BY You are joining many tables, and the columns in the ORDER BY are not all from the first nonconstant table that is used to retrieve rows.
    猜你喜欢
    • 2012-10-06
    • 2022-10-24
    • 1970-01-01
    • 2011-01-22
    • 2011-07-07
    • 2018-12-21
    • 2010-12-15
    相关资源
    最近更新 更多