使用解释优化 MySQL 查询

Optimize MySQL Query using explain

我关注SQL

SELECT 计数(*) 从一个 A.evnumber=B.evnumber 上的内部联接 B 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) 添加一个复合索引。这应该允许查询为 table B 获取“使用索引”,表明它只使用索引,它不必读取 table 行。它不会减少您在 rows: 1 中看到的 table B 的数量,但它会帮助 B 更容易加入 D。

有时这种类型的优化会产生很好的结果。对于非常大的 tables,它可以提高性能很多。但是你的 table 很小,所以可能不会有太大的不同。