Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is UNION faster than running separate queries?

I have 7 tables that I could UNION on (wwith a limit of 30)

OR

should I do 7 separate queries (with a limit of 30) and trace through them using PHP.

Which why is faster? More optimal? In the second way I would have to trace through part of the 7 queries simulataneously and find the top 30 I need.

like image 918
cdub Avatar asked Nov 21 '11 05:11

cdub


2 Answers

What is your needs?

As @chris wrote before, this may help you: Complex SQL (Maybe Outer Joins)

select * from (select ... from ... order ... limit 10 )
union all
select * from (select ... from ... order ... limit 10)
 order by ... limit 10

As I know (checked on DB with 50 million rows) - its fater than not using the devired queries.

like image 147
Moshe L Avatar answered Oct 23 '22 05:10

Moshe L


Before making decisions you need at least to run both kinds of queries with MySql's EXPLAIN and analyze results. Something like this:

EXPLAIN SELECT f1, f2, f3 FROM t1
    UNION ALL
       SELECT f1, f2, f3 FROM t2;
like image 27
ioseb Avatar answered Oct 23 '22 05:10

ioseb