繁体   English   中英

使用解释优化 MySQL 查询

[英]Optimize MySQL Query using explain

我有以下 SQL

SELECT COUNT(*) FROM A INNER JOIN B ON A.evnumber=B.evnumber INNER JOIN D ON B.userid=D.userid

这是解释结果。

[
{
    "id": "1",
    "select_type": "SIMPLE",
    "table": "A",
    "type": "index",
    "possible_keys": "evnumber",
    "key": "evnumber",
    "key_len": "768",
    "ref": null,
    "rows": "13926",
    "Extra": "Using where; Using index"
},
{
    "id": "1",
    "select_type": "SIMPLE",
    "table": "B",
    "type": "ref",
    "possible_keys": "evnumber,UserID",
    "key": "evnumber",
    "key_len": "768",
    "ref": "A.evnumber",
    "rows": "1",
    "Extra": "Using where"
},
{
    "id": "1",
    "select_type": "SIMPLE",
    "table": "D",
    "type": "ref",
    "possible_keys": "mdl_userinfodata_usefie_ix",
    "key": "mdl_userinfodata_usefie_ix",
    "key_len": "8",
    "ref": "B.UserId",
    "rows": "134",
    "Extra": "Using where; Using index"
}

]

当我执行这个 SQL 时,需要 40 秒。 根据行列值的乘积(13926x134x1=1,866,084),我认为这是不可能的。 请帮助我,我该如何改进? MySQL版本是5.6

该查询已经使用了连接索引,但它没有使用 B 的覆盖索引。这是我能看到的唯一可能的改进。

我会在 B 上为列(evnumber, user_id)添加一个复合索引。 这应该允许查询获得表 B 的“使用索引”,表明它只使用索引,它不必读取表行。 它不会减少您rows: 1 ,但它有助于使 B 更容易加入 D。

有时这种类型的优化会产生很好的效果。 对于非常大的表,它可以大大提高性能。 但是你的桌子很小,所以它可能没有那么大的区别。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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