gpt4 book ai didi

mysql - 提高Mysql查询性能(使用explain类型索引)

转载 作者:行者123 更新时间:2023-11-29 06:51:01 25 4
gpt4 key购买 nike

大家好,我有以下数据库:

`Users`
'id', 'char(36)', 'NO', 'PRI', NULL, ''
'password', 'varchar(64)', 'NO', '', NULL, ''
'email', 'varchar(60)', 'NO', 'UNI', NULL, ''
'roles', 'longtext', 'NO', '', NULL, ''
'is_active', 'tinyint(1)', 'NO', '', NULL, ''

`Galleries`
'id', 'char(36)', 'NO', 'PRI', NULL, ''
'user_id', 'char(36)', 'NO', 'MUL', NULL, ''
'name', 'varchar(255)', 'NO', '', NULL, ''
'description', 'longtext', 'YES', '', NULL, ''
'created_at', 'datetime', 'NO', '', NULL, ''

`Images`
'id', 'char(36)', 'NO', 'PRI', NULL, ''
'gallery_id', 'char(36)', 'YES', 'MUL', NULL, ''
'original_filename', 'varchar(255)', 'NO', '', NULL, ''
'filename', 'varchar(255)', 'NO', '', NULL, ''
'description', 'longtext', 'YES', '', NULL, ''

以及以下查询:

SELECT gal.name, gal.description, img.filename, img.description FROM `homestead`.`users` AS users
LEFT JOIN `homestead`.`galleries` AS gal ON users.id = gal.user_id
LEFT JOIN `homestead`.`images` AS img on img.gallery_id = gal.id
WHERE img.description LIKE '%dog%';

在此查询中使用 explain 时,我在 Users 查询的 type 字段中获得 index 结果。我的问题是,有什么方法可以改进这个查询,从而改善这个结果。我知道索引意味着它会遍历该特定表上的所有条目,在这种情况下这可能是必要的。

但是你们还看到其他改进方法吗?

编辑:显示画廊和图像表的索引:

画廊:

'galleries', '0', 'PRIMARY', '1', 'id', 'A', '1', NULL, NULL, '', 'BTREE', '', ''
'galleries', '0', 'UNIQ_F70E6EB7BF396750', '1', 'id', 'A', '1', NULL, NULL, '', 'BTREE', '', ''
'galleries', '1', 'IDX_F70E6EB7A76ED395', '1', 'user_id', 'A', '1', NULL, NULL, '', 'BTREE', '', ''

图片:

'images', '0', 'PRIMARY', '1', 'id', 'A', '4', NULL, NULL, '', 'BTREE', '', ''
'images', '0', 'UNIQ_E01FBE6ABF396750', '1', 'id', 'A', '4', NULL, NULL, '', 'BTREE', '', ''
'images', '1', 'IDX_E01FBE6A4E7AF8F', '1', 'gallery_id', 'A', '4', NULL, NULL, 'YES', 'BTREE', '', ''

以及对没有用户表的查询的解释:

'1', 'SIMPLE', 'gal', NULL, 'ALL', 'PRIMARY,UNIQ_F70E6EB7BF396750', NULL, NULL, NULL, '1', '100.00', NULL
'1', 'SIMPLE', 'img', NULL, 'ref', 'IDX_E01FBE6A4E7AF8F', 'IDX_E01FBE6A4E7AF8F', '109', 'homestead.gal.id', '1', '25.00', 'Using where'

最佳答案

首先,您可以将左联接更改为内联接——where子句已经这样做了,但要明确。您还可以删除 users,因为它没有被使用。

SELECT g.name, g.description, i.filename, i.description
FROM `homestead`.`galleries` g INNER JOIN
`homestead`.`images` i
ON i.gallery_id = g.id
WHERE i.description LIKE '%dog%';

此查询应该适合 images(gallery_id) 上的索引。

如果性能确实是一个问题,您可能需要研究全文索引,以便将 like 更改为 match()

关于mysql - 提高Mysql查询性能(使用explain类型索引),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47497881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com