首页 > 解决方案 > 查询极慢——使用 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

标签: mysqlspringgoogle-cloud-platform

解决方案


我用每个 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 查询会告诉您您正在使用文件排序(这很糟糕!):

在索引之后,这看起来好多了:


推荐阅读