I have a SQL query that has 4 UNIONS and 4 LEFT JOINS. It is layed out as such:
SELECT ... FROM table1
LEFT JOIN other_table1
UNION SELECT ... FROM table2
LEFT JOIN other_table2
UNION SELECT ... other_table3
LEFT JOIN other_table3
UNION SELECT ... FROM table4
LEFT JOIN other_table4
Would it be better to run 4 separate queries and then merge the results with php after the fact? Or should I keep them together? Which would provide that fastest execution?
The most definitive answer is to test each method, however the
UNIONis most likely to be faster as only one query is run by MySQL as opposed to 4 for each part of the union.You also remove the overhead of reading the data into memory in PHP and concatenating it. Instead, you can just do a
while()orforeach()or whatever on one result.