MySQL查询优化——索引

标签 mysql sql-optimization

我有这些表:

CREATE TABLE  `cstat` (
  `id_cstat` bigint(20) NOT NULL,
  `lang_code` varchar(3) NOT NULL,
  `description` varchar(255) NOT NULL,
  `description_tr` varchar(255) NOT NULL,
  `id_ccountry` varchar(3) NOT NULL,
  `geometry_point` point DEFAULT NULL,
  `geometry_poly` polygon DEFAULT NULL,
  `name_type` varchar(1) NOT NULL,
  `bb_min_lat` double DEFAULT NULL,
  `bb_min_lon` double DEFAULT NULL,
  `bb_max_lat` double DEFAULT NULL,
  `bb_max_lon` double DEFAULT NULL,
  `has_ex` tinyint(1) NOT NULL DEFAULT '0',
  `order` int(11) DEFAULT NULL,
  PRIMARY KEY (`id_cstat`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE  `dstat` (
  `id_cstat` bigint(20) NOT NULL,
  `lang_code` varchar(3) NOT NULL,
  `word` varchar(30) NOT NULL,
  `word_no` tinyint(3) unsigned NOT NULL,
  `word_cnt` tinyint(3) unsigned NOT NULL,
  `word_grp` tinyint(3) unsigned NOT NULL,
  `name_type` char(1) CHARACTER SET ascii NOT NULL,
  `cstat_order` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

我需要使用 dstat 中的条件并按照 cstat.order 或 dstat.cstat_order 的顺序从 cstat 中选择一条记录。

我的查询是这样的:

SELECT cstat.ID_CSTAT, cstat.LANG_CODE, cstat.DESCRIPTION, cstat.DESCRIPTION_TR, cstat.ID_CCOUNTRY, AsBinary(cstat.GEOMETRY_POINT) AS GEOMETRY_POINT, cstat.NAME_TYPE, cstat.BB_MIN_LAT, cstat.BB_MIN_LON, cstat.BB_MAX_LAT, cstat.BB_MAX_LON, cstat.HAS_EX
FROM cstat cstat
JOIN dstat W0
ON (W0.ID_CSTAT = cstat.ID_CSTAT)
where
  (W0.WORD = 'ceska') AND
  (W0.NAME_TYPE = 'B')
ORDER BY W0.CSTAT_ORDER;

谁能帮我创建什么索引来防止使用文件排序?我相信我已经尝试了几乎所有的方法,但我失败了。此基本查询有更多修改(表 dstat 的另一个或多个连接,但现在这并不重要)。

非常感谢您的帮助。

编辑:老实说——我已经尝试了很多索引。我声明的基础是 cstat_id_cstat 上的主键。目前我有以下索引:

KEY `ix_dstat_nt_word_id_order` (`name_type`,`word`,`id_cstat`,`cstat_order`);
KEY `ix_dstat_word_id_order` (`word`,`id_cstat`,`cstat_order`);
KEY `ix_dstat_nt_grp_no_word_id_order` (`name_type`,`word_grp`,`word_no`,`word`,`id_cstat`,`cstat_order`);
KEY `ix_dstat_grp_no_word_id_order` (`word_grp`,`word_no`,`word`,`id_cstat`,`cstat_order`);
KEY `ix_dstat_nt_grp_word_id_order` (`name_type`,`word_grp`,`word`,`id_cstat`,`cstat_order`);

这部分解决了我的索引阅读问题。但是排序总是通过使用 filesort 进行的。

解释

1, 'SIMPLE', 'W0', 'ref', 'ix_dstat_nt_word_id_order,ix_dstat_word_id_order,ix_dstat_nt_grp_no_word_id_ord‌​er,ix_dstat_nt_grp_word_id_order', 'ix_dstat_nt_word_id_order', '93', 'const,const', 1, 'Using where; Using index; Using filesort' 
1, 'SIMPLE', 'cstat', 'eq_ref', 'PRIMARY,ix_cstat_id_order', 'PRIMARY', '8', 'search_2012_q3_cze_svk_dev.W0.id_cstat', 1, ''

最佳答案

看起来你应该在 cstat.id_cstat 上有一个索引 一个在 dstat for word 和 name_type

关于MySQL查询优化——索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13124443/

相关文章:

mysql - 将变量从 PHP 脚本传递到过程 Mysql

oracle order by 运行速度非常慢

mysql - 大数据量执行速度更快吗[MySQL]

sql-server - SQL Server 查询优化?

sql - 如何在 SSMS 中显示批量中单个查询的实际查询计划?

mysql - 关于MySQL按日期筛选数据的问题

添加触发器时MySQL工作台错误1064

MySQL 搜索一个字母单词

phpmyadmin - 有没有免费的 MYSQL 数据库分析器工具?

mysql - 如何最大限度地减少MySQL选择查询的时间?