任何帮助将不胜感激。
我有两张桌子:
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`username_canonical` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`email_canonical` varchar(255) NOT NULL,
`enabled` tinyint(1) NOT NULL,
`salt` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`last_login` datetime DEFAULT NULL,
`locked` tinyint(1) NOT NULL,
`expired` tinyint(1) NOT NULL,
`expires_at` datetime DEFAULT NULL,
`confirmation_token` varchar(255) DEFAULT NULL,
`password_requested_at` datetime DEFAULT NULL,
`roles` longtext NOT NULL COMMENT '(DC2Type:array)',
`credentials_expired` tinyint(1) NOT NULL,
`credentials_expire_at` datetime DEFAULT NULL,
`messages_unread_count` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UNIQ_1483A5E992FC23A8` (`username_canonical`),
UNIQUE KEY `UNIQ_1483A5E9A0D96FBF` (`email_canonical`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
和
CREATE TABLE `blog_posts` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) DEFAULT NULL,
`category_id` int(11) DEFAULT NULL,
`title` varchar(255) NOT NULL,
`content` longtext NOT NULL,
`tags` varchar(512) NOT NULL,
`timestamp_created` datetime NOT NULL,
`timestamp_updated` datetime NOT NULL,
`is_visible` tinyint(1) NOT NULL,
`is_deleted` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_78B2F93212469DE2` (`category_id`),
KEY `IDX_78B2F932A76ED395` (`user_id`),
CONSTRAINT `FK_78B2F932A76ED395` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
CONSTRAINT `FK_78B2F93212469DE2` FOREIGN KEY (`category_id`) REFERENCES `blog_categories` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
我希望选择所有帖子限制输出的帖子作者,给我一个建议 - 我怎么能强制查询使用索引:
select p.*, u.* from blog_posts p join users u on p.user_id = u.id limit 0,10;
解释输出:
+----+-------------+-------+------+----------------------+----------------------+---------+----------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+----------------------+----------------------+---------+----------+------+-------------+
| 1 | SIMPLE | u | ALL | PRIMARY | NULL | NULL | NULL | 1 | |
| 1 | SIMPLE | p | ref | IDX_78B2F932A76ED395 | IDX_78B2F932A76ED395 | 9 | sky.u.id | 1 | Using where |
+----+-------------+-------+------+----------------------+----------------------+---------+----------+------+-------------+
加入用户表时有没有办法使用索引?
答案 0 :(得分:0)
如果您在blogposts.userid和users.id之间设置FK关系,Mysql将自动使用索引。
所以创建FK关系:
CONSTRAINT blogposts_userid FOREIGN KEY (user_id) REFERENCES users (id)