mysql - 查询极慢——使用 google sql cloud
问题描述
有没有办法可以加快速度?现在,查询需要花费令人难以置信的疯狂时间。
SELECT trades.*, trader1.user_name as trader1_name,
trader2.user_name as trader2_name FROM trades
LEFT JOIN logs_players trader1 ON trader1.user_id = trader1_account_id
LEFT JOIN logs_players trader2 ON trader2.user_id = trader2_account_id
ORDER BY time_added
LIMIT 20 OFFSET 0;
在网上搜索解决方案方面,我已尽我所能。或者甚至只是试图获得更多信息,为什么它需要这么长时间才能执行。
查询大约需要 45 秒左右才能完成。
创建语句:
CREATE TABLE `trades` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`trader1_account_id` int(11) DEFAULT NULL,
`trader2_account_id` int(11) DEFAULT NULL,
`trader1_value` bigint(20) DEFAULT NULL,
`trader2_value` bigint(20) DEFAULT NULL,
`trader1_ip` varchar(16) DEFAULT NULL,
`trader2_ip` varchar(16) DEFAULT NULL,
`world` int(11) DEFAULT NULL,
`x` int(11) DEFAULT NULL,
`z` int(11) DEFAULT NULL,
`level` int(11) DEFAULT NULL,
`trader1_user` varchar(12) DEFAULT NULL,
`trader2_user` varchar(12) DEFAULT NULL,
`time_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8
CREATE TABLE `logs_players` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`user_name` varchar(20) DEFAULT NULL,
`world_stage` varchar(20) DEFAULT NULL,
`world_type` varchar(20) DEFAULT NULL,
`bank` longtext,
`inventory` longtext,
`equipment` longtext,
`total_wealth` mediumtext,
`total_play_time` mediumtext,
`rights` int(11) DEFAULT NULL,
`icon` int(11) DEFAULT NULL,
`ironmode` int(11) DEFAULT NULL,
`x` int(11) DEFAULT NULL,
`z` int(11) DEFAULT NULL,
`level` int(11) DEFAULT NULL,
`last_ip` varchar(16) DEFAULT NULL,
`last_online` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`muted_until` timestamp NULL DEFAULT NULL,
`banned_until` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8
解决方案
我用每个 10k 行填充了一个示例数据库,发现一些索引是您需要的:
ALTER TABLE `logs_players` ADD INDEX(`user_id`);
ALTER TABLE `trades` ADD INDEX(`time_added`);
我们需要的主要索引是user_id
. 将我们的查询时间从 20.1390 秒更改为 0.0130秒:
我们甚至可以进一步降低它,通过在 time_add 上添加一个索引来加快排序速度,现在我们得到了令人印象深刻的查询时间:
对索引进行一些研究!一个简单的 EXPLAIN 查询会告诉您您正在使用文件排序(这很糟糕!):
在索引之后,这看起来好多了:
推荐阅读
- html - 卡片头的引导垂直对齐
- javascript - 如何禁用列拖动并保持分组功能
- c++ - 为什么 const int 对 char 大括号 init 很好?
- amazon-web-services - 如何在 serverless.yml 中将 DynamoDB 流引用为 Lambda 函数触发事件?
- r - RSelenium - remDr$switchToWindow() 没有按预期工作(不切换窗口)
- pytorch - 我可以在不下载数据集的情况下从“torchvision.datasets.ImageNet”获取类列表吗?
- r - 从 R 中另一个更大的列表中搜索到一个非常大的列表
- git - 创建发布分支时如何使用 git hooks 来增加版本号?
- django - 从列表中选择用户并添加到发布请求
- swift - 按钮,如何在导航栏中嵌入的swiftUI中打开新视图