【发布时间】:2018-06-27 08:15:05
【问题描述】:
我的 mysql 数据库表有问题。我在表中有超过 2000 万行。表结构如下所示。主要问题是查询需要很长时间才能执行(有些查询需要超过 20 秒)。我尽可能使用索引,但是许多查询使用日期范围,并且在日期范围内我的索引不起作用。同样在查询中,我几乎使用每一列。我需要更改我的数据表以提高效率吗?
`history` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`barcode` varchar(100) DEFAULT NULL,
`bag` varchar(100) DEFAULT NULL,
`action` int(10) unsigned DEFAULT NULL,
`place` int(10) unsigned DEFAULT NULL,
`price` decimal(10,2) DEFAULT NULL,
`old_price` decimal(10,2) DEFAULT NULL,
`user` int(11) DEFAULT NULL,
`amount` int(10) DEFAULT NULL,
`rotation` int(10) unsigned DEFAULT NULL,
`discount` decimal(10,2) DEFAULT NULL,
`discount_type` tinyint(2) unsigned DEFAULT NULL,
`original` int(10) unsigned DEFAULT NULL,
`was_in_shop` int(10) unsigned DEFAULT NULL,
`cate` int(10) unsigned DEFAULT NULL COMMENT 'grupe',
`sub_cate` int(10) unsigned DEFAULT NULL,
`comment` varchar(255) DEFAULT NULL,
`helper` varchar(255) DEFAULT NULL,
`ywd` varchar(255) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`deleted_at` timestamp NULL DEFAULT NULL
)
PRIMARY KEY (`id`),
KEY `barcode` (`barcode`) USING BTREE,
KEY `action` (`action`) USING BTREE,
KEY `original` (`original`) USING BTREE,
KEY `created_at` (`created_at`) USING BTREE,
KEY `bag` (`bag`) USING BTREE
ENGINE=InnoDB
我的一些疑问:
select SUM(amount) as amount,
SUM(comment) as price,
cate
from `history`
where ( `action` = '4'
and `place` = '28'
and `created_at` >= '2018-04-01 00:00:00'
and `created_at` <= '2018-04-30 23:59:59'
)
and `history`.`deleted_at` is null
group by `cate`;
select cate,
SUM(amount) AS kiekis,
SUM(IF(discount>0,(price*amount)-discount,(price*amount))) AS suma,
SUM(IF(discount>0,IF(discount_type=1,(discount*price)/100,discount),0)) AS nuolaida
from `history`
where ( `history`.`action` = '4'
and `history`.`created_at` >= '2018-01-01 00:00:00'
and `history`.`created_at` <= '2018-01-23 23:59:59'
)
and LENGTH(barcode) > 7
and `history`.`deleted_at` is null
group by `cate`;
【问题讨论】:
-
请。在帖子中也显示查询
-
我们需要知道您遇到的问题类型,以便能够提供任何有意义的指导。我猜你从不在查询中使用
id,这只是一个代理键?如果是这种情况,那么您可能会考虑将id改为唯一约束,并将主键更改为在提取数据时更有帮助的东西。主键定义了数据物理存储的顺序(聚集索引),所以如果您总是按条形码查询,那么将其用作主键可能更有意义? -
添加了我的一些查询以发布。我不能使用条形码作为我的主要,因为我有多行具有相同的条形码。
-
向我们展示
explain计划,尝试其他索引、LENGTH(barcode) 上的虚拟列索引或 deleted_at 列上的索引,或者添加一个标志列 IsDeleted 作为布尔值而不是测试 null /not null 值并且有一个包含很多值的索引