简体   繁体   中英

Any way to make UNION ALL run faster?

I have a lot of exactly same tables. TableA,TableB,TableC,TableD etc. which I want to create views from. Doing select * from TableA takes 20ms, doing select * from tableB takes 20ms, but doing (select * from TableA) union all (select * from TableB) takes over 20 minutes. Those tables have exactly same columns. Is there any settings in my.cnf that I need to change, or a way to create a view that would run faster? All tables have 1.5m to about 10m rows.

Results of explain

PRIMARY TableA  ALL                 28808685    
UNION   TableB  ALL                 15316215    
UNION RESULT    <union1,2>  ALL     Using temporary

Table structure: 10 varchar(20)'s, 5 unsigned INTs.

My guess is that select * from TableA does not take 20 ms. It takes 20 ms to start returning results.

Although I am going to answer your question, you should revisit your data structure. Having multiple tables with the same layout is usually a really bad idea. Instead, you should have a single table with all the rows.

But, you don't seem to have that.

Try running the union all without parentheses:

select * from TableA union all
select * from TableB;

MySQL has a habit of materializing subqueries. I'm not sure if it does this with union all subqueries, but given your description of the problem, that sees likely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM