如何启用 mysql 为我的表使用索引
Posted
技术标签:
【中文标题】如何启用 mysql 为我的表使用索引【英文标题】:how to enable mysql to using index for my table 【发布时间】:2018-01-08 07:02:39 【问题描述】:CREATE TABLE `sqq_merchant`.`other_coupon_order` (
`id` int NOT NULL AUTO_INCREMENT ,
`tenant_id` varchar(32) NOT NULL ,
`store_id` varchar(64) NOT NULL ,
`order_no` varchar(64) NOT NULL ,
`out_order_no` varchar(64) NOT NULL ,
`total_fee` integer NOT NULL DEFAULT 0 ,
`other_coupon_fee` integer NOT NULL DEFAULT 0 ,
`act_total_fee` integer NOT NULL DEFAULT 0 ,
`pay_method` tinyint(4) NOT NULL DEFAULT 0 ,
`trade_time` datetime NOT NULL ,
`create_time` datetime NOT NULL ,
`update_time` datetime NOT NULL ,
PRIMARY KEY (`id`),
INDEX `tenant_store_id` (`tenant_id`, `store_id`) USING BTREE ,
UNIQUE INDEX `order_no` (`order_no`) USING BTREE
);
我想查询定义的租户、定义的商店和定义的交易时间范围的订单,例如:
select * from other_coupon_order where tenant_id = '9001' and store_id = '1151610006' and
trade_time > '2018-01-08 00:00:00' AND trade_time < '2018-01-08 23:59:59'
当我对这个sql使用explain时,我发现type是All,性能很差,我该如何改进这个sql
这是解释的sql性能图
【问题讨论】:
您的表中有多少行?如果mysql发现使用索引比不使用索引扫描表更便宜,它就会使用索引。您可以将trade_time
添加到复合索引 tenant_store_id
中,其顺序与 where 子句中列出现的顺序相同,但如果 mysql 使用索引有意义,则将使用该索引
是的,这很有帮助,谢谢
@money - WHERE
子句中的顺序无关紧要。重要的是把 =
列放在首位,可选择以一个“范围”列结尾。
【参考方案1】:
您也可以尝试将 trade_time 添加到复合索引中,为 (tenant_id, store_id, trade_time)
INDEX my_indx_name (tenant_id, store_id, trade_time)
【讨论】:
以上是关于如何启用 mysql 为我的表使用索引的主要内容,如果未能解决你的问题,请参考以下文章
如何在 MI 4i 安全应用程序中以编程方式为我的应用程序启用自动启动选项?