为什么MySQL在主索引上采用独特的索引?
我有2个非常简单的表如下:
create table company(
company_id int auto_increment,
company_no varchar(20),
company_name varchar(20),
primary key(company_id),
unique index uni_company_no(company_no)
);
create table department(
department_id int auto_increment,
department_no varchar(20),
department_name varchar(20),
company_id int not null,
primary key(department_id),
unique index uni_department_no(department_no),
index idx_company_id(company_id)
);
如果我用follwing sql查询(我知道这是一个奇怪的查询),请说明Statenment的结果表明MySQL采用唯一的索引(uni_company_no)而不是主键:
explain select dept.* from department dept right join company com on dept.company_id = com.company_id;
我的问题是:
- 为什么MySQL不为Table Company使用Full Table Scan?
- 如果MySQL决定使用索引,为什么不使用Table Company的主要钥匙?
我是MySQL的新手,因此任何输入都可能会有所帮助。提前致谢。
I have 2 very simple tables created as below:
create table company(
company_id int auto_increment,
company_no varchar(20),
company_name varchar(20),
primary key(company_id),
unique index uni_company_no(company_no)
);
create table department(
department_id int auto_increment,
department_no varchar(20),
department_name varchar(20),
company_id int not null,
primary key(department_id),
unique index uni_department_no(department_no),
index idx_company_id(company_id)
);
And if I query with the follwing SQL(I know it's an odd query), the result of EXPLAIN statenment shows that MySQL takes unique index(uni_company_no) instead of primary key:
explain select dept.* from department dept right join company com on dept.company_id = com.company_id;
My questions are:
- Why didn't MySQL use full table scan for table company?
- Why didn't MySQL take primary key of table company if it decides to use index?
I'm very new to MySQL, so any input could be helpful. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想可能有MySQL中有缓存,我关闭缓存并删除唯一的索引并查询两次。答案是相同的(添加唯一索引更快)。
I guess there maybe have cache in MySQL, I turn cache off and drop unique index and query two times. the answer is same (add unique index is faster).