【发布时间】:2016-11-18 09:43:30
【问题描述】:
我创建了一个名为“myview”的视图,如下所示。
create view myview
as select 'a' source,col1,col2
from table_a
union
select source,col1,col2
from table_b
;
table_a 在col1 上有一个索引,table_b 在source 上有一个索引,col1。当我如下查询myview时,没有使用索引。
select *
from myview
where source = a
and col1 = 'xxx'
;
如何使索引在此查询中起作用?
创建代码
CREATE TABLE `table_a` (
`col1` VARCHAR(50) NULL DEFAULT NULL,
`col2` VARCHAR(50) NULL DEFAULT NULL,
INDEX `table_a_idx01` (`col1`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM
;
CREATE TABLE `table_b` (
`source` VARCHAR(50) NULL DEFAULT NULL,
`col1` VARCHAR(50) NULL DEFAULT NULL,
`col2` VARCHAR(50) NULL DEFAULT NULL,
INDEX `table_b_idx01` (`source`, `col1`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM
;
create view myview
as select 'a' source,col1,col2
from table_a
union
select source,col1,col2
from table_b
INSERT INTO table_a (col1, col2)
VALUES
('test', 'testcol2'),
('test', 'testcol2'),
('test', 'testcol2'),
('test', 'testcol2'),
('test', 'testcol2'),
('test', 'testcol2');
INSERT INTO table_b (source,col1, col2)
VALUES
('b','test2', 'testcol2'),
('b','test2', 'testcol2'),
('b','test2', 'testcol2'),
('b','test2', 'testcol2'),
('b','test2', 'testcol2'),
('b','test2', 'testcol2');
解释
explain
select *
from table_a
where col1 = 'test'
id,select_type,table,type,possible_keys,key,key_len,ref,rows,Extra
1,SIMPLE,table_a,ref,table_a_idx01,table_a_idx01,153,const,5,Using index condition
explain
select *
from table_b
where source = 'b'
and col1 = 'test'
id,select_type,table,type,possible_keys,key,key_len,ref,rows,Extra
1,SIMPLE,table_b,ref,table_b_idx01,table_b_idx01,306,const,const,1,Using index condition
在 myview 上解释
explain
select *
from myview
where source = 'b'
and col1 = 'test'
id,select_type,table,type,possible_keys,key,key_len,ref,rows,Extra
1,PRIMARY,<derived2>,ref,<auto_key0>,<auto_key0>,306,const,const,1,Using where
2,DERIVED,table_a,ALL,\N,\N,\N,\N,6,\N
3,UNION,table_b,ALL,\N,\N,\N,\N,6,\N
\N,UNION RESULT,<union2,3>,ALL,\N,\N,\N,\N,\N,Using temporary
如您所见,视图选择时没有调整索引。
【问题讨论】:
标签: mysql performance indexing view union