0

I have created a view in MySQL as

create view vtax
as
SELECT * FROM table1 
union
SELECT * FROM table2;

Where in table 1 have 800000 records, and table2 have 500000 records, when I run the independent queries the result are returned with 0.078 secs, but when I am running them through the view it goes in toss taking time more than 10-15 secs.

select * from vtax where col1=value; -- takes more than 10-15 secs

select * from table1 where col1=value; -- takes 0.078 secs

select * from table2 where col1=value; -- takes 0.078 secs

I have created indexes on the tables separately.

Any help/idea what should be done.

Strawberry
  • 33,750
  • 13
  • 40
  • 57
NKS
  • 1,140
  • 4
  • 17
  • 35

3 Answers3

3

UNION

performs a distinct over your results (often a sort). Can you use

UNION ALL

? (ie. are the rows distinct?)

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
0

You should compare apples with apples. Unions are often much slower than simple queries. Compare the an union with the view. You will notice that the standard union query is slow as well. Probably the optimizer has problems with the decision for the optimal path. Check some other questions like: Why are UNION queries so slow in MySQL?

Community
  • 1
  • 1
Udo Held
  • 12,314
  • 11
  • 67
  • 93
0

As stated in the comments a view isn't indexed in MySQL.

If you use the union in the query:

SELECT * FROM table1 WHERE col1 = 'value'
UNION
SELECT * FROM table2 WHERE col1 = 'value'

Then indexes (if there are any) can be used.

Gervs
  • 1,397
  • 9
  • 8