mysql表应该添加什么类型的索引?
这些是mysql表应该添加什么类型的索引?,mysql,sql,indexing,Mysql,Sql,Indexing,这些是mysql表,下面是查询 CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `email` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ); CREATE TABLE `posts` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id
mysql
表,下面是查询
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
);
CREATE TABLE `posts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned NOT NULL,
`message` text NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
您会向posts
表中添加什么类型的索引,以使此查询高效地工作
谢谢您的建议。您已经在
用户上建立了索引。由于使用了唯一键,因此电子邮件
。这将根据您的电子邮件条件优化行选择
主键users.id
隐式地是索引的一部分,它将用于在posts
中查找匹配的行
然后,您需要在posts
上建立一个索引,以便每个相应的users.id
可以有效地找到匹配的行。索引还应在处为范围条件创建的上有第二列
select COUNT(1)
from posts inner
join users on posts.user_id = users.id
where email = 'test@gmail.com'
and created_at > DATE(NOW() - INTERVAL 30 DAY);
您可以看到这是如何影响EXPLAIN的,并可以看到使用了索引
新索引之前:
ALTER TABLE posts ADD INDEX (user_id, created_at);
+----+-------------+-------+------------+-------+---------------+-------+---------+-------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+-------+---------------+-------+---------+-------+------+----------+-------------+
| 1 | SIMPLE | users | NULL | const | PRIMARY,email | email | 1022 | const | 1 | 100.00 | Using index |
| 1 | SIMPLE | posts | NULL | ALL | NULL | NULL | NULL | NULL | 1 | 100.00 | Using where |
+----+-------------+-------+------------+-------+---------------+-------+---------+-------+------+----------+-------------+
posts
上的join将被强制执行表扫描
新索引之后:
ALTER TABLE posts ADD INDEX (user_id, created_at);
+----+-------------+-------+------------+-------+---------------+-------+---------+-------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+-------+---------------+-------+---------+-------+------+----------+-------------+
| 1 | SIMPLE | users | NULL | const | PRIMARY,email | email | 1022 | const | 1 | 100.00 | Using index |
| 1 | SIMPLE | posts | NULL | ALL | NULL | NULL | NULL | NULL | 1 | 100.00 | Using where |
+----+-------------+-------+------------+-------+---------------+-------+---------+-------+------+----------+-------------+
连接到posts
使用索引
您可能会喜欢我的演示文稿,或者喜欢我的演示文稿。外键用户id的索引