Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 索引,其中条件仅出现在“中”;可能的“U键”;_Mysql_Sql - Fatal编程技术网

Mysql 索引,其中条件仅出现在“中”;可能的“U键”;

Mysql 索引,其中条件仅出现在“中”;可能的“U键”;,mysql,sql,Mysql,Sql,我在MySQL 5.7中有一个查询,比如: select c1,count(distinct c2) as cnt from tbA where c3 >= '2020-09-01 00:00:00' and c3 < '2020-09-02 12:00:00' group by 1 为什么c3的索引只出现在“可能的_键”中而没有最终使用?如何使用此索引 表架构: CREATE TABLE `tbA` ( `id` bigint(20) NOT NULL, `c2`

我在MySQL 5.7中有一个查询,比如:

select c1,count(distinct c2) as cnt from tbA 
where c3 >= '2020-09-01 00:00:00' and c3 < '2020-09-02 12:00:00' 
group by 1
为什么c3的索引只出现在“可能的_键”中而没有最终使用?如何使用此索引


表架构:

CREATE TABLE `tbA` (
  `id` bigint(20) NOT NULL,
  `c2` int(11) DEFAULT NULL,
  `c1` int(11) DEFAULT NULL,
  `channel_id` int(11) DEFAULT NULL,
  `c3` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `audit_create` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `audit_update` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  PRIMARY KEY (`id`),
  KEY `idx_uid` (`c1`),
  KEY `login_time` (`c3`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
MySQL(可能还有其他所有数据库)只使用一个索引访问一个表

解释计划告诉您的是,它正在考虑使用任何一种索引,
c1
c3
,但它认为
c1
是最好的


通过在
(c1,c3)
上使用复合索引,您可以稍微帮助查询。但是,不能在同一个表引用上使用两个单独的索引。

c3
存储日期时间值,但它有VARCHAR数据类型。@Akina Yes。此表由logstash JDBC输出插件传输,原始的
postgres
表的时间列类型为
text
。因此,我使用
varchar
存储时间,但是列本身是索引的,在这里的查询中只能使用一个索引。因此,优化器必须选择其中一个可能的。您可能希望在这里的两列上试验复合索引,并检查这是否提高了性能。
CREATE TABLE `tbA` (
  `id` bigint(20) NOT NULL,
  `c2` int(11) DEFAULT NULL,
  `c1` int(11) DEFAULT NULL,
  `channel_id` int(11) DEFAULT NULL,
  `c3` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `audit_create` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `audit_update` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  PRIMARY KEY (`id`),
  KEY `idx_uid` (`c1`),
  KEY `login_time` (`c3`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci