I created a view named 'myview' as below.
create view myview
as select 'a' source,col1,col2
from table_a
union
select source,col1,col2
from table_b
;
table_a
has an index on col1
, table_b
has an index on source
, col1
. When I query on myview
as below, no index is used.
select *
from myview
where source = a
and col1 = 'xxx'
;
How do I make the indexes work on this query?
Create Code
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
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
Explain on 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