Is UNION faster than running individual queries?

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

OR

Should I make 7 separate requests (with a limit of 30) and track them using PHP.

Why is this faster? Optimal? In the second case, I would have to trace part of 7 queries at the same time and find the 30 best I need.

+4
source share
3 answers

What are your needs?

As @chris wrote earlier, this can help you: Complex SQL (possibly external joins)

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

As I know (tested on a database with 50 million rows) - its richer than not using missed queries.

+3
source

Before making decisions, you need to at least run both types of queries with MySql EXPLAIN and analyze the results. Something like that:

EXPLAIN SELECT f1, f2, f3 FROM t1 UNION ALL SELECT f1, f2, f3 FROM t2; 
+2
source

depends on whether each query will produce unique results using UNION ALL, you better save server trips, and you can sort the result after the join. eg,

  select column1 alias1, column2 alias2, from table x where ... UNION ALL select column3 alias1, column2 alias2 from table y where ... ... order by 1 

Sorry my english

0
source

Source: https://habr.com/ru/post/1382216/


All Articles