假设你有一张像
CREATE TABLE `t1` (
`search_id` int(11) NOT NULL,
`provider_id` bigint(20) unsigned NOT NULL,
`status` text NOT NULL,
`imported_at` int(11) NOT NULL,
`created_at` int(11) NOT NULL,
`latitude` double DEFAULT NULL,
`longitude` double DEFAULT NULL,
`moderation` tinyint(3) NOT NULL DEFAULT '0',
PRIMARY KEY (`search_id`,`provider_id`),
KEY `k_search_imported` (`search_id`,`imported_at`),
KEY `k_scm` (`search_id`,`created_at`,`moderation`),
KEY `k_sc` (`search_id`,`created_at`)
) ENGINE=InnoDB;
我不确定的是为什么
SELECT COUNT(1) FROM t1;
需要 19 分钟(我已经用 120 万行填充了表格)。
MariaDB [test] 10:53:58> show indexes from t1;
+-------+------------+-------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+-------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| t1 | 0 | PRIMARY | 1 | search_id | A | 13478 | NULL | NULL | | BTREE | | |
| t1 | 0 | PRIMARY | 2 | provider_id | A | 646982 | NULL | NULL | | BTREE | | |
| t1 | 1 | k_search_imported | 1 | search_id | A | 30 | NULL | NULL | | BTREE | | |
| t1 | 1 | k_search_imported | 2 | imported_at | A | 46213 | NULL | NULL | | BTREE | | |
| t1 | 1 | k_scm | 1 | search_id | A | 8 | NULL | NULL | | BTREE | | |
| t1 | 1 | k_scm | 2 | created_at | A | 646982 | NULL | NULL | | BTREE | | |
| t1 | 1 | k_scm | 3 | moderation | A | 646982 | NULL | NULL | | BTREE | | |
| t1 | 1 | k_sc | 1 | search_id | A | 10 | NULL | NULL | | BTREE | | |
| t1 | 1 | k_sc | 2 | created_at | A | 646982 | NULL | NULL | | BTREE | | |
+-------+------------+-------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
9 rows in set (0.00 sec)
我想知道这里的问题是否是基数。我的问题是 InnoDB 索引是否应该按更靠近索引开始的更高基数列排序,即PRIMARY KEY (provider_id,search_id);
它是否重要?
因此,正如@RickJames 在其中一条评论中建议的那样,基数与索引的顺序关系不大。因此,如果您的查询类似于
那么索引应该是有序的
search_id,provider_id
。但是,如果您正在运行更多基于范围的查询。这意味着每当您有如下查询时。
那么你的索引应该创建如下
columnX,search_id,provider_id
。