我正在使用MySQL 8,但对于如何选择要在不同查询中使用的索引,我仍然有疑问
表格如下:
CREATE TABLE IF NOT EXISTS `collection_stats` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`date` DATE NOT NULL,
`org_uuid` BINARY(16) NOT NULL,
`project_uuid` BINARY(16) NOT NULL,
`collection_name` VARCHAR(255) NOT NULL,
`counter1` BIGINT UNSIGNED NOT NULL DEFAULT 0,
`counter2` BIGINT UNSIGNED NOT NULL DEFAULT 0,
`counter3` BIGINT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
INDEX `date_index` (`date` ASC),
INDEX `org_usage_index` (`org_uuid` ASC, `date` DESC),
INDEX `project_usage_index` (`org_uuid` ASC, `project_uuid` ASC, `date` DESC),
UNIQUE INDEX `collection_usage_index` (`org_uuid` ASC, `project_uuid` ASC, `collection_name` ASC, `date` DESC))
ENGINE = InnoDB;
想法是,我有一些按组织,项目,集合组织的每日统计信息(一个组织可以有多个项目,而一个项目可以有多个集合)。
我想查看最近X天每个组织,每个项目或每个集合的counter1
,counter 2
和counter 3
的值。
explain SELECT
org_uuid, project_uuid, collection_name,
counter1, counter2, counter3
FROM collection_stats
WHERE
org_uuid = UUID_TO_BIN('bb5c2330-1a85-11e9-8ad9-b728a2ed4173', 1) AND
date >= DATE_SUB(NOW(), INTERVAL 10 DAY)
# id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, Extra
'1', 'SIMPLE', 'collection_stats', NULL, 'ref', 'collection_usage_index,date_index,org_usage_index,project_usage_index', 'collection_usage_index', '16', 'const', '8', '100.00', 'Using index condition'
我看到它使用的是collection_usage_index
而不是org_usage_index
,但我对此没有任何解释。
explain SELECT org_uuid, project_uuid, collection_name, counter1, counter2, counter3 FROM collection_stats
WHERE
org_uuid = UUID_TO_BIN('bb5c2330-1a85-11e9-8ad9-b728a2ed4173', 1) AND
project_uuid = UUID_TO_BIN('faafad18-1a85-11e9-8a1d-b7281ece80f6', 1) AND
date >= DATE_SUB(NOW(), INTERVAL 10 DAY)
解释同样。使用collection_usage_index
代替project_usage_index
..
对此有任何逻辑解释。我的表只有几行要测试?可能是原因吗?
答案 0 :(得分:0)
您正在WHERE
子句中使用函数。就我所知,MySQL无法使用函数和索引。
您可以通过将date >= DATE_SUB(NOW(), INTERVAL 10 DAY)
更改为DATE >= $DATE
并进行检查来进行验证。